In C, what is the behavior of executing printf("%d %d %d %d ", i, ++i, i--, i++); with int...
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
In C, what is the behavior of executing printf("%d %d %d %d\n", i, ++i, i--, i++); with int i = 6;?
Show answer & explanation
Answer: A. The evaluation order of function arguments is unspecified / produces undefined behavior
In C (pre-C99 and C99), the order of evaluation of function arguments is unspecified, meaning the compiler is free to evaluate them in any order. Additionally, this code modifies i multiple times (via ++i, i--, and i++) without an intervening sequence point between the modifications, which violates the C standard and results in undefined behavior. Any specific output is unreliable and non-portable.
Step-by-step Derivation:
Analysis:
- The expression
printf("%d %d %d %d\n", i, ++i, i--, i++);contains multiple modifications to variablei. - In the argument list:
i(read),++i(modify),i--(modify),i++(modify). - C Standard rule: Between sequence points, a variable must not be modified more than once, and if modified, no other value of that variable may be accessed except to determine the new value.
- Here, there is no sequence point between the four argument evaluations, and
iis both read and modified multiple times. - The evaluation order of function arguments is unspecified (not left-to-right guaranteed) in C.
- Result: Undefined Behavior — the program may output anything, crash, or behave differently on different compilers/systems.
- Options B and C assume a fixed evaluation order (left-to-right), which is not guaranteed in C.
- Option D is incorrect because the code compiles successfully; it just exhibits undefined runtime behavior.