Is this undefined C behaviour?

前端 未结 8 999
我在风中等你
我在风中等你 2020-11-29 06:26

Our class was asked this question by the C programming prof:

You are given the code:

int x=1;
printf(\"%d\",++x,x+1);

What output w

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 06:47

    What output will it always produce ?

    It will produce 2 in all environments I can think of. Strict interpretation of the C99 standard however renders the behaviour undefined because the accesses to x do not meet the requirements that exist between sequence points.

    Most students said undefined behavior. Can anyone help me understand why it is so?

    I will now address the second question which I understand as "Why do most of the students of my class say that the shown code constitutes undefined behaviour?" and I think no other poster has answered so far. One part of the students will have remembered examples of undefined value of expressions like

    f(++i,i)
    

    The code you give fits this pattern but the students erroneously think that the behaviour is defined anyway because printf ignores the last parameter. This nuance confuses many students. Another part of the student will be as well versed in standard as David Thornley and say "undefined behaviour" for the correct reasons explained above.

提交回复
热议问题