Learning C // Part 2

gcc_warnWithin the last days I read many questions about C on Stackoverflow. Most of them are typical beginners issues struggling with arrays and pointers. Some time ago I wrote this article about »Learning C« which suggests some basic statements. Based on these Stackoverflow issues I wrote some additional statements which should improve your way of thinking in C and your code.

  • Do not ignore compiler warnings. You should always compile with the option -Wall and honor warnings. The compiler is pretty good in detecting odd things and in 99.999% of all cases he is right.
  • Typecast only if you really know what your are doing. If you typecast just to suppress a compiler warning without knowing the reason for it then you’re most probably doing wrong.
  • Understand the memory model. What is the difference between code, BSS, stack and heap (see Data Segment) and how memory is allocated there.
  • An array is not a data type. It is a memory structure. Arrays are handled as implicit pointers to a memory buffer and work similar to the data type »reference« of C++.
  • Make use of qualifier keywords such as const, static, restrict,…, where applicable. They help the compiler to check the plausibility of the code.
  • Do never assume that typically everything will go right. Assume that everything that can go wrong, will go wrong! …which leads to the next statement.
  • Always check the return value of library functions and system calls! (see man pages for their values).
  • And again: C does what you told it to do — in any case! It doesn’t treat you with kid gloves which many other languages do.