Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between preprocessor directive #if and normal if

Tags:

What is difference between preprocessor directive #if and normal if in C? I'm new to C.

like image 843
kevin Avatar asked Mar 03 '11 02:03

kevin


People also ask

What are the different preprocessor directives?

There are 4 Main Types of Preprocessor Directives: Macros. File Inclusion. Conditional Compilation. Other directives.

What is d difference between preprocessor directives and header files?

Preprocessor directives appear in source code. There are many different directives. One of them is #include , which is used to include a header file. Header files contain a collection of declarations, often for functions and types (and sometimes variables) found in a library.

What are preprocessor directives in C definition?

What Does Preprocessor Directive Mean? Preprocessor directives are lines included in a program that begin with the character #, which make them different from a typical source code text. They are invoked by the compiler to process some programs before compilation.

What are preprocessor directives explain with example?

Preprocessing directives are lines in your program that start with # . The # is followed by an identifier that is the directive name. For example, #define is the directive that defines a macro. Whitespace is also allowed before and after the # .


1 Answers

Statements with # in front of them are called preprocessor directives. They are processed by a parser before the code is actually compiled. From the first search hit using Google (http://www.cplusplus.com/doc/tutorial/preprocessor/):

Preprocessor directives are lines included in the code of our programs that are not program statements but directives for the preprocessor. These lines are always preceded by a hash sign (#). The preprocessor is executed before the actual compilation of code begins, therefore the preprocessor digests all these directives before any code is generated by the statements.

So a #if will be decided at compile time, a "normal" if will be decided at run time. In other words,

#define TEST 1 #if TEST printf("%d", TEST); #endif 

Will compile as

printf("%d", 1); 

If instead you wrote

#define TEST 1 if(TEST) printf("%d", TEST); 

The program would actually compile as

if(1) printf("%d", 1); 
like image 121
darda Avatar answered Dec 30 '22 01:12

darda