Friday, 27 May 2016

c++ - `y=++y`, is this standard compliant? [which appears in a test by Microsoft]




I know this looks familiar but it is brought to me as a problem in a test by Microsoft to recruit interns. It seems to me that y=++y is not standard compliant, but I think maybe it would be better to be sure (not sure that I'm better than those who write up these tests at MS). So I'm asking your advice. Do you think expressions like this is standard-compliant and does not result in undefined behaviour?



#include 
int main(){
int a = 10;
int b = 10;

a = ++a; //What ???
b = b++; //What ???
printf("%d %d\n",a,b);
return 0;
}


gcc complains about it when used to compile with -Wsequence-point. (It is not explicitly stated whether it is a C or C++ specific problem.)



But only four answers provided:




a) 10 10
b) 11 10
c) 10 11
d) 11 11


Although one is not restricted to select only one answer ( so maybe I should choose all four? )



Well, in my opinion, between self-incrementing and assignment there is no sequence point. So this violates the specification. Doesn't it?



Answer



They're both well-defined behaviour as per C++11. C++11 doesn't even have sequence points, so a sequence-point related warning is obviously outdated. The assignment operator imposes sequencing on its arguments.



Edit:



Whilst everyone can agree that i = ++i is now well-defined behaviour, it is rather non-trivial to decide the definedness of i = i++. Intuitively, I should describe it as well-defined, but the Standard clearly states that



i = i++ + 1;



is UB, and I'm not seeing the + 1 making any difference here.



The short is, if you wanted to answer this question, you would need to be an expert on the decidedly non-trivial C++11 sequencing rules, which it appears that I am not, but it appears that the answer is "None of the above because UB".


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...