this post was submitted on 17 Mar 2025
1391 points (99.6% liked)

Programmer Humor

35909 readers
406 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
[–] barsoap@lemm.ee 0 points 2 months ago* (last edited 2 months ago) (7 children)

~~i <= 9, you heathen. Next thing you'll do is i < INT_MAX + 1 and then the shit's steaming.~~

I'm cooked, see thread.

[–] formulaBonk@lemm.ee 2 points 2 months ago (5 children)

If it was correct it wouldn’t have been copied into the forums lmao

[–] barsoap@lemm.ee 1 points 2 months ago* (last edited 2 months ago) (4 children)

I mean i < 10 isn't wrong as such, it's just good practice to always use <= because in the INT_MAX case you have to and everything should be regular because principle of least astonishment: That 10 might become a #define FOO 10, that then might become #define FOO INT_MAX, each of those changes look valid in isolation but if there's only a single i < FOO in your codebase you introduced a bug by spooky action at a distance. (overflow on int is undefined behaviour in C, in case anyone is wondering what the bug is).

...never believe anyone who says "C is a simple language". Their code is shoddy and full of bugs and they should be forced to write Rust for their own good.

[–] kevincox@lemmy.ml 5 points 2 months ago* (last edited 2 months ago) (1 children)

But your case is wrong anyways because i <= INT_MAX will always be true, by definition. By your argument < is actually better because it is consistent from < 0 to iterate 0 times to < INT_MAX to iterate the maximum number of times. INT_MAX + 1 is the problem, not < which is the standard to write for loops and the standard for a reason.

[–] barsoap@lemm.ee 2 points 2 months ago* (last edited 2 months ago) (1 children)

You're right, that's what I get for not having written a line of C in what 15 years. Bonus challenge: write for i in i32::MIN..=i32::MAX in C, that is, iterate over the whole range, start and end inclusive.

(I guess the ..= might be where my confusion came from because Rust's .. is end-exclusive and thus like <, but also not what you want because i32::MAX + 1 panics).

[–] barubary@infosec.exchange 0 points 2 months ago (1 children)
for (int i = INT_MIN; ; i++) {    ...    if (i == INT_MAX) break;}
[–] barsoap@lemm.ee 1 points 2 months ago

Would you be bold enough to write if (i++ == INT_MAX) break? The result of the increment is never used, but an increment is being done, at least syntactically, and it overflows, at least theoretically, so maybe (I'm not 100% sure) the compiler could be allowed to break out into song because undefined behaviour allows anything to happen.

load more comments (2 replies)
load more comments (2 replies)
load more comments (3 replies)