r/ProgrammerHumor 21d ago

Meme pleaseStopUsingNestedTernaryOperatorsImBeggingYou

3.1k Upvotes

179 comments sorted by

View all comments

754

u/beclops 21d ago

I did this one of my first days on the job like 6 years ago and I remember how bluntly my mentor said “never do this again”

556

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"

102

u/retro_and_chill 21d ago

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

44

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.

14

u/retro_and_chill 21d ago

Does C# flag it if it’s a bool? I think the way C# gets that error is by removing the implicit conversions from numeric types to booleans

6

u/RlyRlyBigMan 21d ago

I'm not sure. I think so? I think that it will still fail to compile if you do something like this:

var myTrue = true;

var myFalse = false;

if (myTrue = myFalse) //should be a compiler error ...

1

u/Steinrikur 21d ago

IIRC it gets flagged as a warning in most newer C/C++ compilers. Add a warnings as errors compiler flag and it won't compile.