Is scientific notation safe for integer constants in C?

前端 未结 6 740
心在旅途
心在旅途 2021-02-03 18:04

For a while, I\'ve been representing large powers of 10 in constants using scientific notation, just so I don\'t have to count the zeros. e.g.

#define DELAY_USE         


        
6条回答
  •  灰色年华
    2021-02-03 19:01

    It seems that gcc assumes a constant defined using scientific notation as a floating point number unless it is cast.

    A simple C code shows this:

    #include 
    
    #define DELAY_USEC_FP  1e6
    #define DELAY_USEC_INT (unsigned int) 1e6
    
    int main()
    {
        printf("DELAY_USEC_FP: %f\n", DELAY_USEC_FP);
        printf("DELAY_USEC_INT: %u\n",  DELAY_USEC_INT);
        return 0;
    }
    

    On a x86-64 machine, gcc generates this assembly code ($ gcc -S define.c):

    [...]
    ; 0x4696837146684686336 = 1e6 in double-precision FP IEEE-754 format
    movabsq $4696837146684686336, %rax
    [...]
    call    printf
    movl    $1000000, %esi
    [...]
    call    printf
    movl    $0, %eax
    

    As stated here, 10e15 and 10e22 are the maximum power of ten numbers that have an exact representation in simple and double-precision floating-point format, respectively.

    Larger power of ten numbers can not be represented using 32-bit or 64-bit integer types.

提交回复
热议问题