The "type" of symbolic constants?

  • When it is advisable to include type conversion in a symbolic constant / macro, for example:

    #define MIN_BUF_SIZE ((size_t) 256) 

    Is this a good way to make it behave like a real variable with type checking?

  • When it is advisable to use the suffixes L or U (or LL ):

     #define NBULLETS 8U #define SEEK_TO 150L 
+6
source share
4 answers

You need to do this at any time when the default type is not suitable. What is it.

+4
source

Entering a constant can be important in places where automatic conversions are not applied, in particular, functions with a variable argument list

 printf("my size is %zu\n", MIN_BUF_SIZE); 

can easily work when the widths of int and size_t different and you wouldn’t do the cast.

But your macro leaves room for improvement. I would do it like

 #define MIN_BUF_SIZE ((size_t)+256U) 

(see small + sign, is there?)

When defining such a macro, you can still use it in preprocessor expressions (with #if ). This is due to the fact that in the preprocessor (size_t) is evaluated as 0 , and therefore the result is also unsigned 256 .

+4
source

#define is just a preprocessor token insert.

No matter what you write in #define , it will replace with replacement text before compiling.

So any way is right

 #define A a int main { int A; // A will be replaced by a } 

There are many options in #define , such as variadic macro or multiline macro

But the main goal of #define is the only one mentioned above.

0
source

Explicit type specifying in a constant was more relevant in Kernighan and Richie C (before ANSI / Standard C and prototypes of its functions came).

Function prototypes, such as double fabs(double value); , now allow the compiler to generate the correct type conversions if necessary.

In some cases, you still want to explicitly specify constant sizes. Examples that come to me now are bit masks:

  • #define VALUE_1 ((short) -1) can be 16 bits long, while #define VALUE_2 ((char) -1) can be 8. Therefore, when using long x , x & VALUE_1 and x & VALUE_2 will give completely different results .

    • This will also be the case for the suffix L or LL: constants will use different numbers of bits.
0
source

All Articles