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

Discussion

What is the output of this C code?

#include <stdio.h>
    void foo(int*);
    int main()
    {
        int i = 10;
        foo((&i)++);
    }
    void foo(int *p)
    {
        printf("%d\n", *p);
    }

 

  • A.10
  • B.Some garbage value
  • C.Compile time error
  • D.Segmentation fault/code crash

Answer: C

Correct answer: Compile time error

&i produces a value, not an lvalue, and ++ requires an operand it can modify. There is nowhere to store the incremented result, so the compiler rejects (&i)++.

The fix is to store the address in a pointer variable first, as the companion question does: int *p = &i; and then p++, which increments an object that exists. The rule is the same one that makes 5++ and (a+b)++ illegal.

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

Post your comment

Please log in or register to post a comment.