Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Type" of symbolic constants?

Tags:

c

  1. When is it appropriate to include a type conversion in a symbolic constant/macro, like this:

    #define MIN_BUF_SIZE ((size_t) 256)
    

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

  2. When is it appropriate to use the L or U (or LL) suffixes:

    #define NBULLETS 8U
    #define SEEK_TO 150L
    
like image 592
potrzebie Avatar asked Nov 22 '12 17:11

potrzebie


People also ask

What are the symbolic constants?

A symbolic constant can be defined by using it as a label or by using it as a . set statement. A symbol can be used as a constant by giving the symbol a value. The value can then be referred to by the symbol name, instead of by using the value itself.

What are the 3 constants used in C?

Primary constants − Integer, float, and character are called as Primary constants. Secondary constants − Array, structures, pointers, Enum, etc., called as secondary constants.


2 Answers

You need to do it any time the default type isn't appropriate. That's it.

like image 184
Carl Norum Avatar answered Nov 14 '22 22:11

Carl Norum


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

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

could easily crash when the width of int and size_t are different and you wouldn't do the cast.

But your macro leaves room for improvement. I'd do that as

#define MIN_BUF_SIZE ((size_t)+256U)

(see the little + sign, there?)

When given like that the macro still can be used in preprocessor expressions (with #if). This is because in the preprocessor the (size_t) evaluates to 0 and thus the result is an unsigned 256 there, too.

like image 45
Jens Gustedt Avatar answered Nov 15 '22 00:11

Jens Gustedt