Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the following C code if the value of ‘p’ is 10 and that of ‘q’ is 15?

#include <stdio.h>
int main()
{
    int p,q;
    printf("Enter two numbers\n");
    scanf("%d",&p);
    scanf("%d",&q);
    #if(4<2>-1)
    printf("%d",q);
    #else
    printf("bye");
    #endif
}

 

  • A.10
  • B.15
  • C.bye
  • D.error

Answer: B

Correct answer: 15

The condition 4<2>-1 looks like a chained comparison but is not one. Relational operators are left-associative, so it groups as (4<2) > -1:

\[ (4 < 2) = 0, \quad 0 > -1 \text{ is true} \]

So the #if branch survives and the program prints q, which is 15. Note the values are read at run time but the branch is chosen at preprocessing time, so the input never affects which printf is compiled.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.