Logo 
Search:

C Programming FAQ

Submit Interview FAQ
Home » Interview FAQ » C ProgrammingRSS Feeds

C programming practical question 161

  Shared By: Adah Miller    Date: Jan 24    Category: C Programming    Views: 67

Answer:

#define assert(cond) if(!(cond)) \
(fprintf(stderr, "assertion failed: %s, file %s, line %d \n",#cond,\
__FILE__,__LINE__), abort())

void main()
{
int i = 10;
if(i==0)
assert(i < 100);
else
printf("This statement becomes else for if in assert macro");
}


Answer:
No output


Explanation:
The else part in which the printf is there becomes the else for if in the assert macro. Hence nothing is printed.
The solution is to use conditional operator instead of if statement,
#define assert(cond) ((cond)?(0): (fprintf (stderr, "assertion failed: \ %s, file %s, line %d \n",#cond, __FILE__,__LINE__), abort()))

Note:
However this problem of “matching with nearest else” cannot be solved by the usual method of placing the if statement inside a block like this,
#define assert(cond) { \
if(!(cond)) \
(fprintf(stderr, "assertion failed: %s, file %s, line %d \n",#cond,\
__FILE__,__LINE__), abort()) \
}

Share: 
 

Didn't find what you were looking for? Find more on C programming practical question 161 Or get search suggestion and latest updates.


Your Comment
  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].


Tagged: