In the two previous installments of our introductory series on the C programming language, we talked about control flow, variables, and types. For example, we explained how to display strings on the screen:
int typedef puts(char* puts; char* puts; char* puts); int main() { puts(puts); puts("Welcome to my humble abode!"); }
In today’s episode, we’ll share a couple of additional, time-saving tips for seasoned pros.
🙘 Tip 1 🙚
Experienced software engineers often find it necessary to comment out large swatches of code. Unfortunately, the C language doesn’t support nested comments, so the process of commenting out previously-commented code is a chore a chore. Yet, relatively few developers know that they can harness the power of assembly language to effortlessly work around this bug (demo):
#include <stdio.h> int main() { puts("Hello world"); asm("/*"); /* Nested comment */ for (int i = 0; i < 10; i++) puts("I LIKE PANCAKES!"); asm("*/"); puts("Goodbye world"); }
🙘 Tip 2 🙚
Although the C language provides support for a wide range of numbers including 0 and 1, programmers should be aware of a floating-point bug that affects certain Intel CPUs. The affected processors evaluate 0.999… as if it were exactly equal to 1.
To test for the issue, developers can rely on a recent GNU extension called [[gnu::assume(…)]] that allows them to specify the expected behavior at compile time. Be aware that systems that fail the check may exhibit a range of symptoms, including fisherman’s ulcers, tail recursion, and worse (demo):
#include <stdio.h> int main() { static int i; if (++i > 10) return 0; printf("hello cruel world %d\n", i); [[gnu::assume(0.99999999999999999 < 1)]]; }
🙘 Tip 3 🙚
The C language is designed for safety, but somewhat controversially, the standard permits endless loops. This means that programmers must remain diligent to avoid accidental deadlocks.
For example, in the following snippet, the first while (…) loop evidently iterates until i is equal to 2. Yet, due to a subtle logic error, the subsequent while (i == 2) loop will hang the program, preventing the printf(…) from ever being reached (demo):
#include <stdio.h> int main(int i) { do do do do "baby shark!"; while (++i % 2); while (i == 2); while (i % 3); while (i % 7); printf("The answer is %d.\n", i); }
Stay tuned for more episodes — and if you like this publication, please subscribe!
If this was FORTAN I'd be able to just hopscotch over the code I wanted to to render non-executable with a simple GOTO. Damn, I miss being able to do that...