-
IF Condition Check
Hi
I have a code:
Code:
#include<stdio.h>
#define assert(cond) if(!(cond))\
printf("assertion failed for condition %s\n",#cond)
main()
{
int x=100;
if(x == 0)
assert(x<100);
else
printf("No assert call\n");
getchar();
return 0;
}
In this assert macro will call only if x is 0.
So normally as first if condition fail, it should come in else and print "No assert Call".
But it is not coming in else part and directly comes to getchar().
Can any body help why this happen?
Thanks
-
It works when you put brackets on the if/else:
Code:
if (x == 0) {
assert(x<100);
} else {
printf("No assert call\n");
}
If you don't want to have brackets, you should encapsulate your assert function in brackets (with a do-while).
-
Your else in code "belongs" to the if in the macro
Code:
if (x == 0)
if (x < 100) printf(...);
else printf("No assert call\n");
getchar();
-
Normally, when you write multi-line macros, you express them as a while loop.
Code:
#define assert(cond) do { \
if(!(cond)) \
printf("assertion failed for condition %s\n",#cond); \
} while ( 0 ) /* trailing ; is deliberately omitted */
When used in something like this
Code:
if(x == 0)
assert(x<100);
else
printf("No assert call\n");
it has the effect of making it seem to the outer level if statement that the assert is a single statement, and the else will bind to the obviously intended if (and NOT the if now buried inside a while loop).