I’m just going through and grading students’ code from an exercise where they had to implement barrier synchronization in C++ using condition variables and what not.
Someone wrote this:
if ( ++finished_threads_ == threads_ ) { … }
This pains me. It was a group of three students. Did everyone understand this? Is each and everyone of the group able to articulate the order of execution here? Also: what gets compared, two numbers or a return value from incrementation and a number? Would the semantics be 100 % equal in some other language?
I’m not a well versed C++ programmer so I’d have to check if I wanted to be completely certain. My gut tells me finished_threads__ is incremented first and the equality comparison executes second, but I wouldn’t bet on my balls here. Also, is the above code somehow different from this:
if ( finished_threads_++ == threads_ ) {…}
I don’t know. I of course have all the capabilities in my brain to find out. But I can tell you I really don’t know. I have actually discussed this at great length with my teacher at the Uni. and we’ve gone through many intricate semantics of order of execution and so forth, but since I’m not writing C++ even monhtly, I really don’t know right now.
One more: does the incrementation hold always or does it depend on the equality comparison?
My point here is that be explicit and write clean code. Use the way that is completely clear and self-documenting from the beginning. If the other person has to think even for half a second what the code means, it’s not clear. Because this adds up. If you have a codebase filled with these little things that bend your mind when someone asks clever questions about them the mental/cognitive/whatever burden of understanding and arguing about the code gets higher.
One nice example is the ++ operator. Or chaining of the + operator. Who cares. After listening to Douglas Crockford’s argumentation for always using
i += 1
over
i++
or
++i
I’ve completely switched over. Think about it. Do you know how those three work in all languages? Do they work always the same or do they work differently depending on the context (chained with equality comparison, for instance)? I’m not sure and I don’t want to use even a millisecond to waste my time to think about something like this. I understand, of course, that ++i is different from i++, and there are most certainly cases where using them makes some other part of your code easier to reason about. But if there isn’t some spesific reason that you can articulate and really argument for using one or the other, always choose the clearest option that comes with the least amount of thinking.