c preprocessor (Part 2)
3.# undef
suppose you have something like this..
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
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.
4.# pragma
The directive is a compiler specific directive which compiler vendors may provide .
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
working example
3.# undef
suppose you have something like this..
01 | # define x 4 |
02 |
03 | # define x 5 |
04 |
05 | int main(){ |
06 |
07 | int z=x; |
08 |
09 | printf ( "%d" ,x); // output 5 |
10 |
11 | } |
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 |
07 | int main() |
08 | { |
09 |
10 | int z = x; |
11 |
12 | printf ( "%d" ,z); // output 9 |
13 |
14 | } |
1 | # undef conflictingname // undefining macro conflictingname in a headerfile. |
2 |
3 | # define conflictingname |
4 |
5 | int main() |
6 | { |
7 | // do some stuff here |
8 | } |
1 | # undef anyname // not an error |
2 | int main() |
3 | { |
4 | // do some stuff here |
5 | } |
The directive is a compiler specific directive which compiler vendors may provide .
1 | # pragma GCC poison x //variable cannot be used |
2 |
3 | int main(){ |
4 |
5 | /*error x is poisoned .It cannot be used anywhere in GCC compiler system.*/ |
6 |
7 | int x; |
8 |
9 | } |
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__ |
01 | # define _LINE_ 98 // error predefined cannot be redefined |
02 | int main() |
03 | { |
04 | // note this is __ not _ |
05 | printf ( "%d\n" ,__LINE__); // will output current line number |
06 | printf ( "%s\n" ,__FILE__); // file name |
07 | printf ( "%s\n" ,__DATE__); // date of execution |
08 | printf ( "%s\n" ,__TIME__); // time of execution |
09 | printf ( "%d\n" ,__STDC__); // Whether the compiler is standard conforming (1) or not |
10 | } |
0 comments: