<- Back
Comments (135)
- susamThe code in the post seems very similar to the one in my own post from 2010: https://susam.net/sequence-points.html int a = 5; a += a++ + a++; I do remember that this particular code snippet (with a = 5, even) used to be popular as an interview question. I found such questions quite annoying because most interviewers who posed them seemed to believe that whatever output they saw with their compiler version was the correct answer. If you tried explaining that the code has undefined behaviour, the reactions generally ranged from mild disagreement to serious confusion. Most of them neither cared about nor understood 'undefined behaviour' or 'sequence points'.I remember one particular interviewer who, after I explained that this was undefined behaviour and why, listened patiently to me and then explained to me that the correct answer was 17, because the two post-increments leave the variable as 6, so adding 6 twice to the original 5 gives 17.I am very glad these types of interview questions have become less prevalent these days. They have, right? Right?
- AardwolfWhat's the reason that C didn't define the order of this?The horrible undefined behavior of signed integer overflow at least can be explained by the fact that multiple CPU architectures handling those differently existed (though the fact that C even 'attracts' its ill-defined signed integers when you're using unsigned ones by returning a signed int when left shifting an uint16_t by an uint16_t for example is not as forgivable imho)But this here is something that could be completely defined at the language level, there's nothing CPU dependent here, they could have simply stated in the language specification that e.g. the order of execution of statements is from left to right (and/or other rules like post increment happens after the full statement is finished for example, my point is not whether the rule I type here is complete enough or not but that the language designers could have made it completely defined).
- sangeeth96I had to fight through school and university in India with my teachers who believed these were legit questions to ask in written exams. Can't 100% blame them since almost all standard-issue textbooks had them and claimed they'd give predictable output. I thought the same until I noticed the weirdness when running them across different compilers and after I read about UB, sequence points and similar quirks in books that are not total garbage.Luckily, I ended up with smug smiles in all those cases after showing them the output from different compilers.
- Boxxed> The interesting thing here is the Undefined Behavior (UB), well... actually two UBs, thanks to which there are three possible correct answers: 11, 12 and 13.No, if you invoke undefined behavior any result at all is possible.
- compiler-guyWith undefined behavior, a conforming compiler can do anything it wants at all, including generating a program that segfaults or something else.But what often happens in practice is that "Bill's Fly-By-Night-C-Compiler-originally-written-in-the-mid-nineties" implemented it in some specific way (probably by accident) and maintains it as a (probably informal) extension. And almost certainly has users who depend on it, and can't migrate for a myriad of reasons. Anyway, it's hard to sell an upgrade when users can't just drop the new compiler in and go.At the language level, it is undefined-behavior, and any code that relies on it is buggy at the language level, and non-portable.Defining it would make those compiler non-conforming, instead of just dependent on defining something that is undefined.Probably the best way forward is to make this an error, instead of defining it in some way. That way you don't get silent changes in behavior.Undefined behavior allows that to happen at the language level, but good implementations at least try not to break user code without warning.Modern compilers with things like UBSan and such makes changing the result of undefined behavior much less of an issue. But most UB is also, "No diagnostic required", so users don't even know they have in their code without the modern tools.
- TimwiThe statement is valid C#, which has left-to-right execution order and no undefined behavior. The answer is 5 + 7 = 12.
- magicalhippoPerhaps I'm just naive and/or have forgotten too much C, not that I knew that much, but I'm a bit perplexed as to why this is UB.It seems like something that should trigger a "we should specify this" reaction when adding these operators, and there is at least one reasonable way to define it which is fairly trivial and easily implementable.
- danbrucMy expectation was none of the four presented. Evaluate left to right, a is five, post-increment, pre-increment, a is seven, 5 + 7 = 12. For right to left I would expect pre-increment, a is six, a is still six, post-increment, a is 7, overwrite with 6 + 6 = 12.
- HelloNurseThe final value of a is that if you write this you are fired. It's worse than a racist joke.
- p0w3n3dOn my CS lectures algorithms professor used this pseudo language when writing an algorithm on a whiteboard : I <- I++ On the next hour another professor was giving lecture on C++ programming. I asked him the question: what would happen if we compiled i = i++ He went into some deep elaboration on it, but reassumed that only idiot would write like this...
- Someone> The interesting thing here is the Undefined Behavior (UB), well... actually two UBs, thanks to which there are three possible correct answers: 11, 12 and 13.There’s UB, so any answer is possible, isn’t it?
- yasonThe only point you can conclude out of these discussions, especially in an interview, that it doesn't matter what the answer happens to be on $CC and $ARCH but you wouldn't want anyone to write stuff like that in the first place.Failing to recognize the dangers would be an instant fail; knowing that something reeks of undefined behaviour, or even potential UB, is enough: you just write out explicitly what you want and skip the mind games.
- tombertI have always hated this crap; the fact that I'm not 100% sure the result of this indicates that maybe the ++ operator (pre or postfix) is something that should be avoided?I don't do a lot of C anymore, but even when I did, I always would do increments on separate lines, and I would do a +=1, or just a = a + 1. I never noticed a performance degradation, and I also don't think my code was harder to read. In fact I think it was easier since I think the semantics were less ambiguous.
- vishnuguptaI am, thankfully, out of this craziness now but it was fun solving ton of such puzzles from Yashavant Kanetkar books while preparing for campus hiring interviews back in 2000. "Test Your C Skills" in particular. Fun times.https://www.scribd.com/document/235004757/Test-Your-C-Skills...
- deepsunWhy do you need Java four times in tests? They are all the same.The main, I would say, defining, feature of Java is "no of undefined behavior". Aka "write once, run everywhere".
- adverbly/sarcasticThis is how to keep simpletons out of your code base. Every numeric constant is defined in terms of a different lang quiz. Works well in JS as well of course. const DEFAULT_SELECTION = true + true const BASE_PRICE = 4 * parseInt(0.0000001) const BILLING_DAY_OF_MONTH = a++ + ++a
- pplonski86I love such puzzles! I used to use a lot ternary operators in C++ but one day friend of mine told me that I shouldn't nest ternary operators too much because code is too complicated to read - he understands code perfectly, he was just worried about younger programmers. Since then I started to use longer versions of code instead of smart shortcuts - to improve readability of code.
- TomteSome C++ quiz with ++a and a++? It‘s always about sequence points, or better the lack of sequence points.It‘s the standard technical C++ blog post everybody seems to write.
- dhosekI don’t have gcc available so I can’t test it, but I wonder what it does with int a = 5; int b = a++; if it gives b==5 in this circumstance (which I would say is the correct value), then it seems that giving 13 for a++ + ++a is a bug in the compiler. I kind of feel like giving 6 as an answer would also be a bug in the compiler since postfix-++ should return the old value and then increment.
- nnm++ should be banned, just like goto
- comrade1234The a=13 was most surprising to me but in retrospect obvious and amusing.
- syngrog66The smart nerd will know precisely how to decode that line's results.The wise nerd will not allow lines like it in their codebase, in the first place and, having seen one, will refactor it (probably involving more lines or parentheses) to make it more clear and easier to maintain.The latter approach scales better, in long run.
- anonundefined
- phendrenad2Tried it on https://www.onlinegdb.com/online_c_compiler Returns 12. If I were designing C, it would return 13. But then again, I'm an assembly programmer.
- summarybot> If you would like to test your compiler (posting back the results in the comments is really appreciated, especially from strange/uncommon compilers and other languages which support pre- / post- increment ....Uh, 85% of them show the wrong result so 85% of them clearly do not support pre and post increment.
- ecshaferhmm surprising. I assumed it would be 12 since 5+5+1+1 doesn't really matter what order you do it in. But I suppose this really undefined behavior.
- onlyrealcuzzoPlease tell me the answer is somehow 42!int a = 5; a = (++a * a++) + --a; a = ?
- nDRDYOh god. How long before yet another UB-based question ends up in technical coding interviews?
- nothrowaways12