2

I'm starting to learn C coming from a background in Java & Javascript and I'm wondering if there is a technical reason for the following being considered bad practice or if it's just the way the language evolved?

#define bool char
#define false 0
#define true 1
#define null NULL

Everywhere I look I always see defined variables (if that's the correct word) uppercased and I'm wondering if there is a good technical reason for this convention? I'm sure this must have been asked many times but I can't seem to find an answer.

LiamRyan
  • 1,892
  • 4
  • 32
  • 61

2 Answers2

7

They're called macros. And yes, by convention they're ALL_UPPERCASE to avoid clashes with normal identifiers, because they're just text replacement and don't follow the normal scoping rules of the language.

Consider the following:

#define foo bar
...
int foo, bar;  // error: preprocessing turns this into int bar, bar;

To avoid surprises like this (code that isn't what it seems like), we try to keep macros distinct.

melpomene
  • 84,125
  • 8
  • 85
  • 148
1

It's not the lowercase definitions are bad (even if there are against common convention), rather than reinventing the language is considered as such:

#define null NULL

This way you are going to confuse maintenance programmer, who expects NULL as idiomatic way to specify null pointer constant.

Grzegorz Szpetkowski
  • 36,988
  • 6
  • 90
  • 137