Lurker News
I have 15+ years of experience in many languages: javascript, python, go, etc.

I can write C, but I'm not confident I'm doing it the right way. There are now decades of forums and blogs I can search through, but I'd love to have a single, clean, clear source of truth for recommendations on how to write C code.
I've started reading "Modern C" by Jens Gustedt. I'm not sure if this is the closest to a modern source of truth.
Note, I'd like my C code to work on Windows, which possibly restricts the "right way" to features provided by C89. But again, I'm not sure, the internet is super clear on this.
Thanks for the tips!

Comments (199) 63 threads

Show all comments

Showing thread 8 of 63

jakobdabo2 replies#
In addition to the other recommendations, make sure you fully understand the memory model of your target architecture, the stack, the heap, the linkage.

Also, understand the undefined behavior, the compiler optimizations and how it can affect your code if you forget about the UB or if you ignore the compiler warnings, and read about the `volatile` keyword.
And a personal tip, please tell the compiler not to use strict aliasing (I think it's stupid) - you will get rid of some UB without much sacrifice.

krychu2 replies#
Just to be clear, heap and stack are not part of C.
Canada2 replies#
Then why does it make a difference whether you dereference a pointer to the stack or the heap at any point in your program?

The hardware representation of an int isn't part of C either but it most certainly had an effect on how your program will run.

clarry4 replies#
> Then why does it make a difference whether you dereference a pointer to the stack or the heap at any point in your program?

Ok, I'll bite. What difference does it make?

Continue this thread — 4 replies

camgunz#
I guess they're not "exclusive" to C, but they're very important in C in a way they aren't in most languages. So I think op's advice here is good.
saagarjha#
> Also, understand the undefined behavior, the compiler optimizations and how it can affect your code if you forget about the UB or if you ignore the compiler warnings, and read about the `volatile` keyword.

PSA: volatile generally doesn't do what you want it to; you almost never want it. volatile does not "fix" undefined behavior.
> And a personal tip, please tell the compiler not to use strict aliasing (I think it's stupid) - you will get rid of some UB without much sacrifice.
This prevents the compiler from performing a number of optimizations.