Is this undefined C behaviour?

2019-01-06 17:06发布

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 will it always produce ?

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

Thanks for the edit and the answers but I'm still confused.

8条回答
唯我独甜
2楼-- · 2019-01-06 17:35

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.

查看更多
放荡不羁爱自由
3楼-- · 2019-01-06 17:39

The points made about undefined behavior are correct, but there is one additional wrinkle: printf may fail. It's doing file IO; there are any number of reasons it could fail, and it's impossible to eliminate them without knowing the complete program and the context in which it will be executed.

查看更多
登录 后发表回答