Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i write preprocessor directives anywhere in my c program?

Is it mandatory to write #include at the top of the program and outside the main function?

I tried using #define preprocessor inside the main function and it worked fine with only one exception..that being the constant which i defined using the define directive can be used only after the line #define For instance say printf("%d",PI); #define PI 3.14will give error "Undefined symbol PI". But in the following code i did not encounter any error

#define PI 3.14 
printf("%d",PI);

Is this because C is a procedural language and procedural languages implements top down approach?

Also i would like to know that can we use only #define inside the main function or other preprocessor directives too? If we can use then which ones? Or is it the other way around, instead of #include we can use all the preprocessor directives in the main function?

like image 206
Techievent.in Avatar asked Jan 29 '23 16:01

Techievent.in


1 Answers

The only place you can't put a preprocessor directive is in a macro expansion. The sole exception is #pragma, which can also be written _Pragma().

This has nothing to do with "procedural", but due to the fact that C is defined in terms of 8 translation phases, each of which is "as-if" fully-completed before the next phase. For more details, see the C11 standard, section 5.1.1.2.


One example of when it is useful to use preprocessor directives after the start of a file is for the "X Macro" technique (which many people only know as "those .def files").

like image 120
o11c Avatar answered Feb 01 '23 11:02

o11c