Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined expression with a definite answer?

Tags:

c

undefined

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?

like image 209
user3742467 Avatar asked Mar 15 '23 21:03

user3742467


1 Answers

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. :-)

like image 152
ruakh Avatar answered Mar 25 '23 09:03

ruakh