Home > OS >  C Is it right to use constexpr in size declaration
C Is it right to use constexpr in size declaration

Time:11-06

I'm trying to make sizes declaration is it right to use constexpr

#define BYTE ((size_t)1)
#define KIB   (constexpr BYTE * (size_t)1024)
#define MIB   (constexpr KIB   * (size_t)1024)
#define GIB   (constexpr MIB   * (size_t)1024)

CodePudding user response:

The constexpr keyword can't be used as part of an expression. It just makes no syntactical sense in the position you are using it. constexpr is a qualifier on a declaration for a variable or function.

There is no point in using a macro like this. You can declare these constants as constexpr variables:

constexpr size_t BYTE = 1;
constexpr size_t KIB = BYTE * 1024;
constexpr size_t MIB = KIB * 1024;
constexpr size_t GIB = MIB * 1024;

You don't even need the constexpr. It will work with just const instead exactly the same. However constexpr makes the intention of these being compile-time constants clearer and will avoid making mistakes causing them not to be compile-time constants.

Also, the explicit casts to size_t are not needed. Usual arithmetic conversions will make sure that the second operand is converted to size_t as well. (I suppose technically it is allowed for size_t to have lower rank than int, in which case it may be a problem, which however can be avoided by using unsigned literals 1024U instead of signed int. But if we are talking about weird platforms like that size_t might also be too small to hold the values you want to compute here.)


Since C 17 it is slightly safer to additionally qualify the variables with inline. This has the effect of giving the variables external linkage while still making it possible to define them in multiple translation units. Otherwise they have internal linkage, which usually is not a problem, however one might take the address of the variable and use it e.g. in the definition of an inline function. Then having internal linkage for the variable would cause an ODR violation on the inline function definition.

  • Related