NewLearner
NewLearner

Reputation: 153

A question regarding #if defined (macro name)

#if defined(_WIN32)
#if !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS 
#endif

So the above is the first 4 lines of C language code from a file of some project.

I do know that #if defined (macro name) means that if the macro is defined, the value of the expression is 1 and if not, then it's 0.

So basically, the first two lines will be either 1 or 0 but what would they do? 1 or 0 just sitting alone?

Upvotes: 1

Views: 61

Answers (3)

alk
alk

Reputation: 70893

So basically, the first two lines will be either 1 or 0 but what would they do? 1 or 0 just sitting alone?

No, the #if would stay, just the defined() would become 0 or 1.

So assuming for example _WIN32 and _CRT_SECURE_NO_WARNINGS were defined, then the 1st two line you show looked like:

#if 1
#if 0

Those two if-statements control if what is following is taken into account until the next #endif statement.

The above snippet though is incomplete and should look like this:

#if 1
#if 0
#define FOO 42
#endif
#endif

The above would not #define FOO.

The below would not #define FOO as well:

#if 0
#if 1
#define FOO 42
#endif
#endif

The following will define FOO:

#if 1
#if 1
#define FOO 42
#endif
#endif

Back to your example code:

The stuff "controlled" by the outer if-statement

#if defined(_WIN32)

is

#if !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS 

The stuff "controlled" by the inner if-statement

#if !defined(_CRT_SECURE_NO_WARNINGS)

is

#define _CRT_SECURE_NO_WARNINGS 

Upvotes: 1

haccks
haccks

Reputation: 105992

It's defined() which will be evaluated to either 0 or 1 and from that value if will decide if it should go to the body. It's like normal if statement.

Upvotes: 3

Swordfish
Swordfish

Reputation: 13134

So basically, the first two lines will be either 1 or 0 but what would they do? 1 or 0 just sitting alone?

#if expression

won't result in a line replaced by the result of expression but the preprocessor will decide upon the value of expressen in

#if expression

controlled text

#endif /* expression */

if it will process the controlled text or not.

Upvotes: 1

Related Questions