1. ## Ambiguity problem

I have an exam question about the ambiguity of if then else.

Code:
```#define testNeg(x) if (x>0) printf("Ouuch\n")

if(a>b)
testNeg(x)

else
printf("Arragh\n");
printf("Thank you");```
When a is 4 and b is -3, the result is
Arragh
Thank you
When a is 4 and b is 3 the result is
Oouch
Thank you
When a is -4 b is -3 the result is
Thank you
But not
Arragh
Thank you

I dont understand how such result is outputted in case3. and by inserting the block characters (curly braces), can someone show me the two versions of matching else to the two ifs. (one version for one if) 2. Originally Posted by cowcow8866 I have an exam question about the ambiguity of if then else.

Code:
```#define testNeg(x) if (x>0) printf("Ouuch\n")

if(a>b)
testNeg(x)

else
printf("Arragh\n");
printf("Thank you");```
When a is 4 and b is -3, the result is
Arragh
Thank you
When a is 4 and b is 3 the result is
Oouch
Thank you
When a is -4 b is -3 the result is
Thank you
But not
Arragh
Thank you

I dont understand how such result is outputted in case3. and by inserting the block characters (curly braces), can someone show me the two versions of matching else to the two ifs. (one version for one if)
First of all, this ain't an ambiguity issue. It's called "What happens when we use macros incorrectly?". Second, the answer to your question will reveal itself once you expand the macro "manually" in the test code. 3. testNeg is a preprocessor macro. The preprocessor basically does fancy text substitution. So give it your best shot. Try writing it out, by replacing testNeg the way the preprocessor would, and try putting in the curly braces yourself. Post that here, and I'll tell you if you're wrong and why. 4. Aside from the preprocessor issue, what is the value of x? You didn't specify. In your code, you actually use testNeg(x) instead of something like testNeg(b). Maybe it was just a typo, but that could be a source of problems as well since the values of a and b might simply trigger the code meant for x. 5. your code resolves to this if you put in the braces:
Code:
```#define testNeg(x) if (x>0) printf("Ouuch\n")

if(a>b) {
if (x > 0) {
printf("Ouuch\n");
}
else {
printf("arrgh\n");
}
}
printf("Thank you");```
now follow the logic of what happens when a = -4 and b = -3. this is a good reason to always use braces in if-else.

edit from MSDN c reference : When nesting if statements and else clauses, use braces to group the statements and clauses into compound statements that clarify your intent. If no braces are present, the compiler resolves ambiguities by associating each else with the closest if that lacks an else. Popular pages Recent additions 