How to check if a constant is suitable at compile time?

I would like to add compile time to the following C ++ code (compiled with Visual C ++ 9):

//assumes typedef unsigned char BYTE;
int value = ...;
// Does it fit into BYTE?
if( 0 <= value && value <= UCHAR_MAX ) {
    BYTE asByte = static_cast<BYTE>( value );
    //proceed with byte
} else {
    //proceed with greater values
}

The problem is UCHAR_MAXboth BYTEindependent typedef, and when this code is ported, it can happen that they come out of sync and the code breaks. So I wanted to do something like this:

compileTimeAssert( sizeof( BYTE ) == sizeof( UCHAR_MAX ) );

but VC ++ 9 creates a "negative index" error when compiling that - it sizeof( UCHAR_MAX )has a value of 4, not 1.

How can I do the compile time check that I want?

+3
source share
5 answers

You can check at compile time that ( (1 << (sizeof(BYTE)*CHAR_BIT)) - 1 ) == UCHAR_MAX.

( , , - , . )

+2

'' std:: numeric_limits <BYTE> :: max() UCHAR_MAX

+5

V++ 9 " " - sizeof (UCHAR_MAX) 4, 1.

, .

#define MAX 255;

, sizeof(MAX) a.k.a (sizeof(255)) 2.3.1/2. , UCHAR_MAX a char, , char

, . , , : int, long INT; int, undefined. , , : int, unsigned int, long int, unsigned long . u U, - : unsigned int, unsigned long int. l L, - , : long int, unsigned long int. ul, lu, uL, Lu, Ul, lU, UL LU, unsigned long int.

, , 1, , , -, . sizeof(MAX) , int , char. , .

+1

UCHAR_MAX - unsigned char. unsigned char 1 . , BYTE 0.. UCHAR_MAX -(UCHAR_MAX/2+1).. UCHAR_MAX/2, , sizeof(BYTE) == 1

, - int BYTE, :

if (!(value & ~(BYTE)-1)) ...
+1

Source: https://habr.com/ru/post/1763053/


All Articles