Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doubt in Conditional inclusion

This is actually extracted from my module (Pre-processor in C)

The conditional expression could contain any C operator except for the assignment operators,increment, and decrement operators.

I am not sure if I am getting this statement or not since I tried using this and it worked.Also for other manipulation a probable work around would be to simply declare macro or function inside the conditional expression,something like this to be precise.

Also I don't understand what is the rationale behind this rule. Could somebody explain?

Thanks

like image 200
Quixotic Avatar asked Aug 31 '26 15:08

Quixotic


1 Answers

You seem to misunderstand what the phrase conditional expression refers to.
In this snippet

#if defined TEST
  int a = 0;
#endif

The conditional expression is the part being tested by the #if, meaning it is the defined TEST part.

The reason that assignment, increment and decrement are not allowed is because those operators want to change a variable, which is nonsensical in the context of the preprocessor.
The preprocessor works entirely based on textual substitution and evaluation of the resulting constant expressions.

If you have this code

#define X a++
#define Y 42

#if X == Y
#endif

Then in the test #if X == Y, first X and Y are replaced by their macro expansion (respectively a++ and 42), resulting in

#if a++ == 42

Next, a is replaced by its macro expansion. As there is no macro a, the replacement is defined to result in 0:

#if 0++ == 42

Now there are no possible macro names left to expand, so the preprocessor tries to evaluate the condition. As there is an attempt to increment the constant 0, this evaluation fails with an error.

like image 54
Bart van Ingen Schenau Avatar answered Sep 03 '26 05:09

Bart van Ingen Schenau