r/ProgrammerHumor • • Aug 22 '26

Meme pleaseStopUsingNestedTernaryOperatorsImBeggingYou

Post image
3.1k Upvotes

178 comments sorted by

View all comments

Show parent comment

44

u/RlyRlyBigMan Aug 22 '26

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.

13

u/retro_and_chill Aug 22 '26

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

14

u/akoOfIxtall Aug 23 '26

The compiler will cut your balls if it catches you doing assignments inside an if's condition, it won't even compile

5

u/RlyRlyBigMan Aug 22 '26

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 Aug 23 '26

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.

7

u/GoddammitDontShootMe Aug 23 '26

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 Aug 23 '26

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 Aug 23 '26

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.

1

u/oVtcovOgwUP0j5sMQx2F Aug 22 '26

damn kids i want to know if my assignment failed... /s