user3742467
user3742467

Reputation: 532

Undefined expression with a definite answer?

I'm trying to understand the answer to an interview question.

The following code is presented:

int x = 5;

int y = x++ * ++x;

What is the value of y?

The answers are presented as a list of multiple choice answers, one of them being 35.

Writing and running this code on my machine results in y being equal to 35.
Therefore I would expect to mark the answer to this question as 35.

However, isn't this expression undefined due to the x++ i.e. the side of effect (the actual incrementation of x) could happen at any time depending on how the compile chooses to compile the code.

Therefore, I would not have thought that you could say for certain that the the answer is 35 as different compilers might produce difference results.

Another possible multiple choice answer is 30, which I would have thought was also viable i.e. if the post increment side effect takes place towards very end of the sequence point.

I don't have the answer key, so it's hard to determine what the would be the best answer to give.

Is this just a poor question or is the answer more obvious?

Upvotes: 4

Views: 90

Answers (3)

David Hoelzer
David Hoelzer

Reputation: 16371

You are correct that this is undefined. However...

Often these questions are designed to make you think and, even though undefined by standard, the questioner may be looking to see if you:

  1. Know what happens "in the real world" most of the time. (I'm not saying this is good, but I am saying that you will find constructs this bad and worse in codebases that you may be asked to take over and maintain.)
  2. Know about operator precedence and order of operations.

Upvotes: 0

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

Undefined behavior means UNDEFINED, sometimes it could be the EXPECTED behavior, it doesn't mean it's DEFINED.

Perhaps they want you to answer what the expected behavior is, which is none since it's undefined behavior.

Upvotes: 2

ruakh
ruakh

Reputation: 183484

You are correct; the Standard does not impose any requirements at all on what this code might do.

If this was a multiple-choice question that required you to choose a specific defined answer, then — whoever wrote the question doesn't understand C as well as you do. Keep that in mind when you decide whether to accept an offer there. :-)

Upvotes: 5

Related Questions