Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between "ifndef" and "if !defined" in C?

I have seen #ifndef ABC and #if !defined (ABC) in the same C source file.

Is there subtle difference between them? (If it is a matter of style, why would someone use them in the same file)

like image 599
onemach Avatar asked Dec 23 '11 15:12

onemach


People also ask

What is the difference between Ifdef and if defined?

The difference between the two is that #ifdef can only use a single condition, while #if defined(NAME) can do compound conditionals.

What does Ifndef mean in C?

In the C Programming Language, the #ifndef directive allows for conditional compilation. The preprocessor determines if the provided macro does not exist before including the subsequent code in the compilation process.

What is the difference between Ifndef and Ifdef?

Use the #ifdef statement when you want to compile a section only if a specified expression has been defined with #define. Use #ifndef when you want to compile a section only if a specified expression has not been defined.

What is the difference between #if and #ifdef in C?

#if checks for the value of the symbol, while #ifdef checks the existence of the symbol (regardless of its value).


2 Answers

No, there's no difference between the two when used that way. The latter form (using defined()) is useful when the initial #if or one of the subsequent #elif conditions needs a more complex test. #ifdef will still work, but it might be clearer using #if defined() in that case. For example, if it needs to test if more than one macro is defined, or if it equals a specific value.

The variance (using both in a file) could depend on specific subtleties in usage, as mentioned above, or just poor practice, by being inconsistent.

like image 52
Dan Fego Avatar answered Sep 20 '22 14:09

Dan Fego


In the context you gave, they are the same: you are just checking for the existence of one macro identifier.

However, the #if form allows you to evaluate expressions, which can be useful.

like image 24
Jerry Penner Avatar answered Sep 20 '22 14:09

Jerry Penner