5 C idioms

 

This chapter covers

  • An overview of macros
  • Using specific macros
  • C-style strings
  • Incorrect data types for Boolean values

C was the main predecessor of C++, and its influence is felt across a broad range of projects. Many early adopters of C++ were C programmers looking for a “better C.” C++ provided compatibility with C with few exceptions. Those exceptions were necessary for better type checking, correctness, and language consistency.

However, there are many areas where C coding never changed, even after the advent of C++. Many programmers learned styles and techniques in C and carried them forward to C++. The compiler rarely complained about any of these approaches. The resulting code compiled and ran—what more could have been expected? However, this transition did not necessarily mean developers began shedding the C idioms and adopting a C++ approach. Much code was written without regard to new ways of expressing the same intent.

Over the intervening years, C++ and C began to diverge more and more. The C99 standard clarified and standardized C, while picking up a few things from C++; C++ adopted some of the innovations of C. The two languages are still separate, but each has fertilized the other.

5.1 Mistake 26: Always declaring variables at the top of a function

5.2 Mistake 27: Depending on macros

5.3 Mistake 28: Misunderstanding NULL

5.4 Mistake 29: Accessing disk files using FILE

5.5 Mistake 30: Using integers for Boolean values

5.6 Mistake 31: Using C-style casts

5.7 Mistake 32: Converting text with atoi

5.8 Mistake 33: Using C-style strings

5.9 Mistake 34: Calling the exit function

5.10 Mistake 35: Preferring arrays to vectors