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
.



Relevant Pages

  • Re: size_t problems
    ... Don't worry about it, Martin. ... int main ... I see no reason why it wouldn't work on a Cray. ... It'll work on lots of platforms, ...
    (comp.lang.c)
  • Re: Non-modifiable index/field values
    ... Martin. ... > reject any row that matches another row in the table on the shadow key ... > pk1 int not null, ... > select @@rowcount ...
    (microsoft.public.sqlserver.programming)
  • Re: History of - if(p) delete p; - ... ?
    ... Martin T. wrote: ... int* p = ... ... I think the code was initially created on Visual Studio 4 and then got ... If you want to port ...
    (microsoft.public.vc.language)
  • Re: 1.1KB RL - Fur Hunter
    ... Martin Read formulated the question: ... specified (there are no implicit return types in C++). ... have a return type of type int, but otherwise its type is implementation-defined. ... storage duration) and calling exit with the return value as the argument. ...
    (rec.games.roguelike.development)
  • Re: How NOT to code
    ... Tell that to the guys running x86-64 systems, where int is 32 bits but ... void * is 64 bits. ... Martin Read - my opinions are my own. ...
    (rec.games.roguelike.development)