Advanced C syntax

One advantage about programming in C only for personal projects is that you can get a deeper inside in all the awesome syntactical possibilities mostly ignored by C++ programmers for various reasons. This starts with comma in expressions and goto for alternative flow control. Ever really entered a situation where goto would be highly valuable to have? If not, you're fine leaving it this way until you need to. There's a reason why the art of goto is not taught anymore but you'll appreciate it's existence if you're just getting far enough. Think about seperation of a function's algorithm, error reporting and success handling. If an error happens, you just jump to an error handler cleaning up everything that was created during runtime and returning or filling an error struct. Same on success to avoid a million repeated success handlers. Expanding this by using more than only success and error labels makes it even more interesting. It can even make stuff more visible and easier to understand - provided you don't spaghetti code and know what's controlled use of goto. RAII (Ressource Acquision Is Initialization) is another good example of where goto fulfills an important role: if an error occurs within a block, you'd jump to an error label cleaning up the created garbage. As all error labels are listed in a way that later occuring errors will also trigger error labels of possible previous errors, you can cleanup all kinds of allocated ressources/memories in exactly the same order. Nice, huh? Well, that's an old trick you can learn via some hidden Wikipedia knowledge or by letting an old C nut teach a few tricks. Or you can find it out yourself, as I did with most of it. Of course does it depend on what you're programming, but more than often you'll benefit from leaving aside contemporary code wasting techniques I can tell you!

No comments: