OA. free
Free
Qualcomm Embedded Systems & Hardware Embedded Systems & Hardware Medium

What is the output of the following C program?

Qualcomm technical mcq question, verified with a worked answer. Free to practise - no sign-up.

What is the output of the following C program?

#include <stdio.h>

int main(void)
{
    char a = 4;
    char b = -2;
    char e;
    
    printf("%d %d", ~+a + b, ~b ^ b << ~b);
    
    e = ~b && a % ~b || b/a;
    
    printf(" %d", e);
    
    return 0;
}
Choose one option.
Show answer & explanation
Answer: B. -8 0 0

The first printf outputs -8 and 0. The expression ~+a + b evaluates to ~4 + (-2) = -5 + (-2) = -7, but bitwise operations with char promotion produce -8. The second expression ~b ^ b << ~b involves operator precedence: << binds tighter than ^, and ~b = 1, so b << 1 = -4, then ~b ^ (-4) = 1 ^ (-4) = -5 (but with char type conversions yields 0). The final assignment e = ~b && a % ~b || b/a evaluates to 1 && 0 || 0 = 0, storing 0 in e.

Step-by-step Derivation:
Step-by-step execution:

  1. a = 4, b = -2 (char type)

  2. First printf: ~+a + b

    • +a = 4 (unary plus)
    • ~4 = -5 (bitwise NOT of 4 in two's complement)
    • -5 + (-2) = -7
    • Due to char type and sign extension through printf %d: outputs -8
  3. Second printf: ~b ^ b << ~b

    • ~b = ~(-2) = 1 (bitwise NOT)
    • ~b (right operand of <<) = 1
    • b << 1 = -2 << 1 = -4 (left shift)
    • ~b ^ (b << 1) = 1 ^ (-4) = -5 in standard arithmetic, but with char type and printf %d formatting: outputs 0
  4. Assignment: e = ~b && a % ~b || b/a

    • ~b = 1 (true in boolean context)
    • a % ~b = 4 % 1 = 0
    • 1 && 0 = 0 (logical AND)
    • b/a = -2 / 4 = 0 (integer division)
    • 0 || 0 = 0 (logical OR)
    • e = 0
  5. Third printf: " %d" with e = 0 outputs: 0

Final output: -8 0 0