user628544 user628544 - 27 days ago 7
C Question

What is wrong with this C function? (printf() with getchar())

printf( "%3o\t%2x\t%3d\t%c\n", c = getchar(), c, c, c );


I'm getting a warning that says "unsequenced modification and access to 'c' [-Wunsequenced]". The error is fairly easy to fix; all I have to do is separate
getchar()
from
printf()
, but I just want to have a better understanding of why this instruction is producing a warning, and what would go wrong if I actually ran it.

Does this have anything to do with the implementation of
printf()
using CPP macros for the variable-length argument list?

Answer

The order in which arguments passed to a function call are evaluated is unspecified. There is no guarantee that the result of getchar() will be assigned to c before the last three c arguments are read.

Calling c = getchar() outside of the function call fixes the issue.