Re: C Test Incorrectly Uses printf() - Please Confirm



On 8/8/2010 2:55 PM, Martin O'Brien wrote:
I took an online C test a few months ago. I actually thought the test
was better than some I've taken, but one question in particular I
think has the wrong answer. The question is this:

What is printed:

int a = 1;
printf("%d", ++a, a + 5);

a. 1
b. 2
c. 7
d. undefined

I selected d. This is the explanation given as to why b is the correct
answer.
[...]

I agree that it is undefined. The fact that the result of "a+5" is not used within the printf() function is irrelevant. The mere act of having both "++a" and "a+5" without a sequence point between is what causes UB.

Otherwise, one would have to argue that this doesn't invoke UB:

int foo(int i)
{
int j = i;
i = i++ + ++i;
[... lots of code that never refers to "i" ...]
return j;
}

Sure, it's not likely on most systems to be a problem, but it's still UB as far as the Standard goes. As I've pointed out, there are CPUs that run multiple operations in parallel. If the generated code were to make both references to "i" in parallel, one a read and another an increment (perfectly legal if not to the same address), it may cause a hardware fault to be generated.

--
Kenneth Brody
.