Ads 468x60px

Friday, October 14, 2011

define in c Tutorial 2

 c preprocessor (Part 2)

 3.# undef
suppose you have something like this..

01# define x 4
02 
03# define x 5
04 
05int main(){
06 
07int z=x;
08 
09printf("%d",x); // output 5
10 
11}
although the output is 5 you can’t trust these type of declarations.If you want to redefine the same macro then first undefine it using #undef
correct way of doing
01# define x 8
02 
03# undef x // x is now unknown to compiler
04 
05# define x 9 // x is 9 now
06 
07int main()
08{
09 
10int z = x;
11 
12printf("%d",z); // output 9
13 
14}
so if you have your own macros and you are in doubt that their names can conflict with the macros defined in header files then first use # undef to undefine these macros.
1# undef conflictingname // undefining macro conflictingname in a headerfile.
2 
3# define conflictingname
4 
5int main()
6{
7// do some stuff here
8}
1# undef anyname // not an error
2int main()
3{
4// do some stuff here
5}
4.# pragma
The directive is a compiler specific directive which compiler vendors may provide .
1# pragma GCC poison x //variable cannot be used
2 
3int main(){
4 
5/*error x is poisoned .It cannot be used anywhere in GCC compiler system.*/
6 
7int x;
8 
9}
here GCC poison is called pragmas.Remember these are  compiler dependent.
So GCC poison will not work on microsoft compilers (will not give an error).You have to read manual of the compiler.
Predefined macro
1_LINE_
2_FILE_
3_TIME_
4_DATE_
5__STDC__
working example
01# define _LINE_ 98 // error predefined cannot be redefined
02int main()
03{
04// note this is __ not _
05printf("%d\n",__LINE__); // will output current line number
06printf("%s\n",__FILE__); // file name
07printf("%s\n",__DATE__); // date of execution
08printf("%s\n",__TIME__); // time of execution
09printf("%d\n",__STDC__); // Whether the compiler is standard conforming (1) or not
10}

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...
 

Sample text

Sample Text