Dec 15, 2011

# Define in C + +, how and how not to do


The main objective of this post is to let them know one of the things that C + + allows but nobody in their right mind should do. And to have them teach then? But that if ever seen in a foreign code pinch_ know what's going on.
Well, first of all, # define is used for two things: define a constant or create a macro. The macros can become somewhat difficult to understand, now only see the issue of the constants. The issue here is that if I put (outside the main) a line like this:
 # Define PI 3.14159265 
... Means that every time we write our program PI, C + + interprets it as 3.14159265. It is a simple substitution.
 # Define <aquí goes <after name> space goes value> 
But the point is that you can do some pretty ugly things with this property. Check out this program:
 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 # Include <iostream>
 using namespace std;

 # Define PI 3.14159265
 # Define NOF_CHAR 50
 Cin.get # define pause (); cin.get ();
 # Define ct court
 # Define cn cin
 # Define false true

 int main ()
 {
     char name [NOF_CHAR] = {0};
     ct <<"Enter your name:";
     cn>> name;
     ct <<"Bye" <<name <<"." <<endl;
     if (false)
         ct <<"PS Pi =" <<PI;
     pause
 } 
We have 6 definitions, ordered by their level of acceptability:
  • # Define PI 3.14159265 # define NOF_CHAR and 50, these illustrate the primary use of # define: a value that is kept constant throughout the execution.
  • Cin.get # define pause (); cin.get ();, it is beginning to be acceptable but we can not take it for good because it helps us to read more about our code. We know that writing cin.get (); cin.get (); our program is paused as a getch (), but using the # define write instead justpause.
  • # Define # define ct cn court and cin, totally unacceptable. Some people use this type of # define's to write less, but really that (in most cases) not worth the savings of characters, we are only making our code less understandable to others.
  • # Define false true, this is more like a joke (and it's amazing really work), but if used as a seriously is striped mother. If you run the code you will see that it does show the line where you print PI is inside even if that one should never go And why do you come in? because falseis true.
So you know how to do and how not to use a # define in C + +, and are no longer 'defenseless' against bad habits programmers.

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Premium Wordpress Themes