kevin
kevin

Reputation: 14065

Difference between preprocessor directive #if and normal if

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

Upvotes: 25

Views: 17625

Answers (3)

Zak
Zak

Reputation: 982

Preprocessor if allows you to condition the code before it's sent to the compiler. Often used to stop header code from being added twice.

edit, did you mean C++, because it was tagged as such? http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/

Upvotes: 5

darda
darda

Reputation: 4155

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);

Upvotes: 28

tvanfosson
tvanfosson

Reputation: 532435

The preprocessor if is handled by the preprocessor as the first step in the program being compiled. The normal if is handled at runtime when the program is executed. The preprocessor directive is used to enable conditional compilation, using different sections of the code depending on different defined preprocessor constants/expressions. The normal if is used to control flow in the executing program.

Upvotes: 3

Related Questions