this post was submitted on 11 Feb 2025
204 points (94.7% liked)

Programmer Humor

20429 readers
2666 users here now

Welcome to Programmer Humor!

This is a place where you can post jokes, memes, humor, etc. related to programming!

For sharing awful code theres also Programming Horror.

Rules

founded 2 years ago
MODERATORS
 
you are viewing a single comment's thread
view the rest of the comments
[–] Kwdg@discuss.tchncs.de 22 points 1 day ago (1 children)

Not needed, main in C++ implicitly returns 0 if there is no return

[–] 30p87@feddit.org 1 points 1 day ago (1 children)

Should ≠ Needs to

You can do it, and it will work, but it's unclean and not best-practice. I wouldn't be surprised if it's undefined behaviour.

[–] xmunk@sh.itjust.works 20 points 1 day ago (1 children)

Just to clarify. It is defined behavior - there's plenty of undefined behavior in C but that ain't one of them.

[–] FuckBigTech347@lemmygrad.ml 2 points 18 hours ago

Interesting feature, I had no idea. I just verified this with gcc and indeed the return register is always set to 0 before returning unless otherwise specified.

spoiler

int main(void)
{
    int foo = 10;
}

produces:

push   %rbp
mov    %rsp,%rbp
movl   $0xa,-0x4(%rbp) # Move 10 to stack variable
mov    $0x0,%eax       # Return 0
pop    %rbp
ret
int main(void)
{
    int foo = 10;
    return foo;
}

produces:

push   %rbp
mov    %rsp,%rbp
movl   $0xa,-0x4(%rbp) # Move 10 to stack variable
mov    -0x4(%rbp),%eax # Return foo
pop    %rbp
ret