why are goto statements ILLEGAL? (should they be?)
Video Title: why are goto statements ILLEGAL? (should they be?)
Are go-tos illegal you’ve probably heard the argument that go-tos make your code unreadable but this code is unreadable and there’s not a go-to in sight so what’s the deal with go-tos in this video we’ll talk about what a go-to is under the hood how you can use go-tos
Incorrectly and how to correctly use them to make your code not only more readable but more efficient let’s Dive Right In to discuss go-tos we need to First understand what a go-to actually is here I’m looking at some code and in the code we do some pretty straightforward stuff if argc is equal
To two which means that we gave it two command line arguments we invoke the goto statement that tells the compiler to insert code that will make the code run at the print label we Define a label which is different from a function that’s just an area of code inside of a
Function with the name of the label and then a colon and then code after that so if we give it to arguments we go to the print label and then we go there and we print that we got two arguments awesome otherwise if this didn’t happen we go to
Leave and then from there we return zero and we can see under the the H it’s actually going on in our program by just doing an object dump tacd Mel on what is and then in main you’ll actually see the exact logic here that we wrote in C in
Assembly if you don’t fully understand assembly that’s okay all we’re doing here is we’re comparing the variable ARG C to two and if it’s not equal we go to one label but if it is equal we go to another label what a go to literally is it inserts a jump instruction in our
Code in assembly now you’re probably wonder ing what does this do for us why would we actually use this and that’s actually a great question because if you look at this code already we’ve began to very heavily obfuscate what the code does and make it very difficult to read
I’m already just looking at this code having a hard time understanding what’s going on so this is a bad example of when go-tos are good and I would argue using logic like this to use go-tos is actually really bad but let’s go to a good example pun intended here I have
Some basic server functionality and obviously this is not broken out into same functions that all do one thing this is all happening in one function but this demonstrates the point that I’m trying to make so to run the server we open a file and like good C programmers
We check that the return value of that open call is a good value and if it’s not we print the error for open we leave our program if we don’t fail if we succeed we move forward and then we maloc room on the Heap to readin data
From that file if that Malo buffer returns null a bad value and again we’re checking for that every time because we’re good SE programmers we have to go and close that file descriptor then go to print the error for Malik then return negative 1 and then if that succeeds we
Call socket check for a bad value and then we have to free the previous buffer we got before we have to close the file that we opened before and what’s Happening Here is we are increasing every time there’s a possible failure the amount of duplicative code that we
Have to insert right because we already have close written here and written here now we have to add free if we have more conditionally failable code that we insert this gets very very ugly to maintain and then even if it succeeds as good programmers we have to close our
File descriptors and free our memory so we have to duplicate this code again this is where go-tos get really magical I’m going to insert goto into this code and show you how you can make it a little bit cleaner so here I’ve Rewritten the code but I’m using goto
Statements and you should immediately see that the code is not only more legible it’s less chaotic and every error State as a Cascade down in the code doesn’t get longer with the duplicate of code like close FD and free Malik for example and by the way if any
Of the syntax is confusing to you I am running a course right now called Zero to Hero C programmer Link in the description below go check it out if you want to learn more about the C language the C syntax really anything C or assembly related so the major change to
The structure is that I’ve put a return value variable at the top of the code that will use to store our return value right it’s zero success and if we return anything other than zero we have a non-success state right and then later on in the code like for example when our
Socket fails right instead of the socket failing and us having to close a file descriptor free Malik and that same code appears all over the place we just do one go to that goto is a label that will then fall through and run all those pieces of code that we had in the
Previous example so instead of having to do free here and close here we can put free at this label and then the next line of code will run it’ll close the FD after that and then return the return value Val which is set to1 and in the
Success case where none of this actually happens and everything succeeds we set the return value equal to zero and after our code runs we close the socket file descriptor we free the file buff we close the FD and we return the success value and you can see the structure is
That the lowest function the one that’s further on in the code goes to the top level error Handler because it has to handle the most things that has to do it has to free the buffer it has to close the file the scriptor ETC while go-to in
A lot of other cases make code a lot harder harder to read using goto to handle error cases allows you to write the same code one time in your error Handler and then use the go-tos to jump to what layer of error handling you’re at now another cool thing about C is
That the switch statement is actually way faster than the if statement and the reason behind it is really interesting you’ll find out about that in this video go go click goodbye
Video Keywords: C++, if statements,switch statements,c programming,c tutorial
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
Check out my new courses at https://lowlevel.academy !
It’s nice to have “finally” in higher level languages 😅
My teacher always got visibly upset when anyone used gotos 😂
You introduced your video in the worst way possible. When you say something like "this code is unreadable, and it doesn't have any goto's" is something that has nothing to do logically with what you said. It's like saying: Killing should be illegal because it's immoral, and then say something like "I stole, and that's also immoral". More info: https://en.wikipedia.org/wiki/Affirming_the_consequent
There should be a difference between educational content, and low level learning. You're showing neither
What compiler are you using?
The one place I rather often use goto is in my custom installers, where I skip several steps or log an error and then jump to the end of a function without using a return.
Yeah I could make function for each step and just do a return in case a bad return code matches, I however like to keep things as less convoluted with methods and functions in installers as possible, which in my past experience makes it easier to maintain.
Hahahahaha goto statements go brrrrrrrrrrrrrrrrrrrrrr
I need "defer" in c, and then, probably, I stop using goto)
Is this example completely solved by Go's defer statement?
simply use rust instead
Fun fact: while(1), while(true), break and continue are all just goto in disguise 😁
the discord link doesn't work
(C++) I actually only ever used goto once because "goto bad". It was when I had a switch statement, and the default case was doing some error handling. If any of the other cases encountered a situation they couldn't handle, they'd goto a label at the default case. I think I was writing a lexer so that kinda makes sense?
Remember that in the end the compiler will "goto" the living shit out your code..as much as it can to produce most efficient, compact code possible.
i've always use goto in my PHP code, it's really make easier.
To me, goto may be useful in some (rare) cases, and I've used multiple times, but practically always this is the result of poor design in initial phase. A function for example that allocates more than one resource isn't a violation of the single responsibility principle? It can probably be split in some smaller function, each one handling the lifetime of one resource, and their errors.
i write c and that was extremely good examples and analogies. especially in text processing goto's are life savers. without them "structured programming" turns against you and the code becomes undebuggable.
Isn't it better to use setjmp and longjmp instead of gotos in cases like this where there is successive possible failures ?
i kind of predicted what you were going to do only i was thinking of a switch statement, which in retrospect won't work because the jumps are for different conditions
Thank you for poking holes in coding dogma.
I always found it an academic discussion. Because as you and I know in assembly a goto (jump) is required.
But in the extension of this discussion also was the “one return per function” something I break all the time these days.
You should use the switch to create state machine in loop. Moving this to its own file may be required or recommended to properly isolate the state machine logic using functions and static data types. goto has a lot of nasty problems and is basically deprecated. On stack overflow there is a good point about escaping multiple nested loops with goto. That is probable safe enough to use it, but I am not sure how many people would agree with me on this.
I always love this argument. Writing high level code without GOTOs creates more readable code. This is mostly true. The funny part is, the compiler generates tons of jumps (gotos) in the final binary, the actual assembly language. Just disassemble a switch statement, or if-then-else. JMP (goto) is there.
why do you use NULL instead of 0? It's literally the same thing, just casted if needed
In general as a rule of thumb, I try to keep GOTOs in the same function scope, so just for loops and the like, it helps keep GOTO reasonably easy to read (and far safer!) but also still gives it a lot of flexibility. Also if I'm writing optimized code, I try to keep branches in general (not specifically GOTOs, they just tend to get messier), to be short and minimal, only things like small if statements, just to avoid the LOADS of cache misses you can cause by putting everything in their own function.
Isn't a jmp assembly instruction literarily a goto?
Code using goto is not only difficult to understand for humans, but also for compilers. If you juse a goto to jump into an inner block, but after the initialization of some variable within that block, this will result in an uninitialized variable when entering the block via the goto. Standard "-Wall" / "-Wextra" / "-pedantic" settings don't give a warning for this, neither in clang nor gcc!
That being said, it is pretty useful for the error handling case shown in the video.
Man…. I've almost bought lifetime access to your courses but then I've watched your video on polymorphism in C++ and why it is slow (or is it) and it kind of made me change my mind. At 3:40 in that video you claim that if a method in a derived class has the same signature as a method in base class the latter will be by default virtual and you seem to claim that virtual keyword is only for readabilty. It is not!
struct A
{
virtual void foo1()
{
std::cout << "foo1 A" << std::endl;
}
void foo2()
{
std::cout << "foo2 A" << std::endl;
}
};
struct B : public A
{
void foo1() override
{
std::cout << "foo1 B" << std::endl;
}
void foo2()
{
std::cout << "foo2 B" << std::endl;
}
};
int main()
{
std::unique_ptr<A> a_ptr = std::make_unique<B>();
a_ptr->foo1();
a_ptr->foo2();
}
foo1 B
foo2 A
That last case you mentioned (the good use of a goto) feels like a switch statement in a way.
I supposed as most languages I use don't have goto, I'd increment or set a numeric variable and then switch() it for error handling.
Great video! I learned a lot 🙂
depends on how well the language handles error conditions. sometimes there's no better way.
A teacher told me that if I used "goto", he would make me fail all the exams I took where I used "goto" and that that sentence should never be used
I haven't used goto statements in C before. This intrigues me, but having started with languages like Atari BASIC where jmp or goto statements were required to do any loops. I never related to the hate for goto statements as the following is perfectly readable to me and seems more intuitive for learning about computers then what modern languages tend to do
10 print "Hello world!"
20 goto 10
or to break after so many cycles
10 x = 0
20 print "Hello world!"
30 x = x + 1
40 if x = 10 then goto 60
50 goto 20
60 …
Though I do appreciate the ability to break thing down into separate functions/libraries in C
When I need to multi-break from multiple loops in one condition I use goto. Sometimes it's just both faster and more readable
I remember even in late Visual Basic programming, there were sometimes esoteric cases where I actually resorted to those old GOTO/GOSUB statements. For example, VB doesn't have a "continue" feature inside loops, so if I needed to do that I'd label the end of the loop (e.g. "ContinueHere:") and GOTO that point.
The very few times when I used GOTO in my C code was always for the reason shown in this video, to avoid duplication of a clean-up code before returning from the function.
The advice to never use GOTO dates back to the ''80s and '90s when many programmers made their first steps with programming in BASIC. This advice was helpful in eliminating bad habits from programming in BASIC.
Old implementations of BASIC had no user-defined functions and usually required IF-THEN statement to be contained in a single line of code. GOTO came in handy to overcome these limitations, but using the same techniques in modern languages was not needed and made the code less readable.
The title and thumbnail of this video are clickbait.
Best way learn x86?