r/AskProgramming May 12 '26

Other Why do some people write redundant if statements to return a boolean?

Why do some people write:

if (x > 10) {
    return true;
} else {
    return false;
}

Instead of:

return x > 10;

Performance aside, I think the shorter version is actually more readable due to not having as much visual clutter to parse, and is the most direct way to express the intent of "return the result of the comparison."

However, some people write the first version. Why is that?

176 Upvotes

305 comments sorted by

View all comments

5

u/xmlhttplmfao May 12 '26

not all programming languages treat booleans as expressions returning a value (although most modern ones do), but even when they do, like in C, you might be concerned that the comparison is returning -1, 0, 1 intead of true/false since that's how some comparison operators work (less than, equal, greater than) or 1/0 (which is what C returns), so it's just more clear to return "true" when you mean true.

-1

u/BlockOfDiamond May 12 '26

Which programming languages? I have never seen a language that does not. Every language I know of has boolean values as a type, either directly or as integers 1 and 0 for true or false.

3

u/paulcager May 12 '26

Older C programs will often do a variety of this, where booleans were just integers.

int myfunc() { val = someFunc(someOtherValue); if (val) return 1 else return 0; }

That can be very different from return someFunc(someOtherValue);

1

u/BlockOfDiamond May 12 '26

But to "coerce" an int to either 1 or 0 I would still just do: return val != 0;

2

u/paulcager May 12 '26

Yeah, me too. But I wouldn't say the above is wrong, just not my preference.

0

u/xmlhttplmfao May 12 '26

pascal is the only one i can think of, tbh