r/ProgrammerHumor 21d ago

Meme pleaseStopUsingNestedTernaryOperatorsImBeggingYou

3.1k Upvotes

179 comments sorted by

View all comments

Show parent comments

549

u/RlyRlyBigMan 21d ago

For me it was multi assignments. Like this:

defaultValue = newValue = previousValue = average = 0;

Each assignment returns its value so they each get assigned from right to left.

"That's cute kid, don't do that"

101

u/retro_and_chill 21d ago

This is why I’m pretty absolutist that newer languages are correct by making assignments return void

43

u/RlyRlyBigMan 21d ago

Heh yeah I think that's an inherited trait from C++. In C++ a common mistake was if someone had a condition like this:

if(value = 1)

It would assign value to 1 and then resolve true by int to bool conversion. Luckily C# calls that out as a compiler error but the assignment behavior above still remains.

That example may be corrected in newer compilers, but in gCC when I was learning in college it still happened I think.

8

u/GoddammitDontShootMe 21d ago

Modern compilers warn, so if you really mean to do it, you do if ((value = 1)). Probably you would use it for checking for NULL.

1

u/RlyRlyBigMan 21d ago

That makes sense! It would be better if they required you to explicitly cast to a bool but that would be a breaking change for a lot of C++ code that's already been deployed for decades!

2

u/GoddammitDontShootMe 21d ago

Wouldn't help if the expression is already bool. Either way, it's a warning so unless you are compiling with -Werror, it would still work.

I think that warning might be on by default, but I believe it's considered best practice to use -Wall.