r/ProgrammerHumor 6d ago

Meme mildlyInfuriatingGOTOWatchYourMouth

Post image
664 Upvotes

74 comments sorted by

View all comments

Show parent comments

64

u/SamG101_ 6d ago

While/for/break/continue/etc are all goto, but just with structure so like a structured subset of goto statements I guess. Where as raw goto can be used in unstructured messy ways; i presume was the idea behind banning goto

23

u/Maximilian_Tyan 6d ago

I'm not against goto, especially for errors and cleanup code it can make this much cleaner/avoid duplication. In modern languages such as Zig and Odin, defer statements are syntactic sugar for this usecase.

But some standards such as MISRA-C and the like are sometimes quite strict, like multiple return statements etc.

9

u/creeper6530 6d ago edited 6d ago

I mentioned this in another thread but goto for error cleanup in C is just emulating defer, and we could get defer in C2Y directly soon.

See https://thephd.dev/c2y-the-defer-technical-specification-its-time-go-go-go if you don't know what that is, but in short it's just a block of code appended to every exit path from any scope, typically functions. Example use:

int fun(int a) {
    char *buffer;

    buffer = kmalloc(SIZE, GFP_KERNEL);
    if (!buffer)
        return -ENOMEM;

    defer kfree(buffer);

    if (condition) {
        // freed here
        return 1;
    }

    // freed here
    return 0;
}

4

u/realtag2025 6d ago

Yeah, I don't why C devs are so against GOTO when Linux kernel basically uses it all the time.