3

I have a question. When I make a #define VAR 5 in c, is it necessary to define the type? like: #define VAR (unit_8) 5

I imagine, what is going on when I make this C code.

#define VAR 15000
void foo(uint_8);
void foo(uint_8 c) { c++; }
int main() {
  foo(VAR);
  return 0; 
}  
Cœur
  • 37,241
  • 25
  • 195
  • 267
pop rock
  • 517
  • 1
  • 6
  • 14
  • It is not necessary, but good practice. That way you can guarantee the data type of the constant. [See this](http://stackoverflow.com/questions/33232075/is-it-reasonable-to-use-enums-instead-of-defines-for-compile-time-constants-in/33232548#33232548) for examples. – Lundin Oct 21 '15 at 08:33

2 Answers2

6

You can't declare variables in #define statements. These are statements only for the preprocessor, and are only text replacements.

VAR in your case is NOT a variable, but a sort of constant that is processed by the preprocessor.

You can do

#define VAR 15000
uint_16 a = VAR;

But VAR itself is decidedly not a variable but only preprocessor text replacement. The compiler will, after the preprocessor has run, treat the above code as;

uint_16 a = 15000;

If you need a constant to use, you can do:

const int VAR = 15000;

Instead.

Magisch
  • 7,312
  • 9
  • 36
  • 52
  • All constants have types though, even if they are not variables. It is good practice to be explicit about which type a certain constant has. There are cases when you cannot use `const` but have to use defines. – Lundin Oct 21 '15 at 08:34
  • @Lundin in these cases you can use something like `#define var (int) 15000` but that doesnt change the fact that its just text replacement. – Magisch Oct 21 '15 at 08:37
5

No, it is not necessary. Macros do textual substitution. They have no idea about data types.

If want to define constants with a type, use const T:

const int var = 15000;

Otherwise, you could, just as you did, cast the constant in the macro:

#define VAR (unit_8) 15000

Note that integer literals may have different types (15000 is always an int). You may adjust the type of a literal by appending suffixes like u, l, etc.

15000lu = unsigned long
16000u = unsigned int
15000 = int
cadaniluk
  • 15,027
  • 2
  • 39
  • 67