Search code examples
cvariablesterminate

Strange behavior when attempting to obtain number of digits of unsigned long long´s maximum


I like the luxury. I wanted to invent a way for you to obtain the number of digits the unsigned long long int maximum possess. All that automatically. Here it is:

#include <limits.h>
#include <string.h>

#define STRINGIFY(x) #x
#define ULLONG_MAX_STRING STRINGIFY(ULLONG_MAX)
#define NUMERAL_MAXIMUM strlen(ULLONG_MAX_STRING)

Does this work as described?


Now about the strange behavior that pretty much answers the question from above. If I declare a variable like so (-std=c99 specific):

char variable [NUMERAL_MAXIMUM];

instead of declaring automatic-scoped variable, array with the size of 20, it terminates the program before it even reaches that line. Though if I don´t declare the variable like so, nothing terminates and the program continues to work.


What is going on?


Update: Even more strange is that the program does that only if I use this obtained length as a size of an array.


Solution

  • IIUC, the OQ wants the size needed to print the maximum values in decimal. The below works for sizes of 8 bits upto 64 bits, at least for CHAR_BIT==8 :

    #include <stdio.h>
    #include <limits.h>
    
    #define ASCII_SIZE(s) ((3+(s) * CHAR_BIT) *4 / 13)
    
    int main(void)
    {
    printf("unsigned char : %zu\n", ASCII_SIZE(sizeof(unsigned char)) );
    printf("unsigned short int : %zu\n", ASCII_SIZE(sizeof(unsigned short int)) );
    printf("unsigned int : %zu\n", ASCII_SIZE(sizeof(unsigned int)) );
    printf("unsigned long : %zu\n", ASCII_SIZE(sizeof(unsigned long)) );
    printf("unsigned long long : %zu\n", ASCII_SIZE(sizeof(unsigned long long)) );
    
    printf("          Ding : %u\n", UINT_MAX );
    printf("     Lang Ding : %lu\n", ULONG_MAX );
    printf("Heel lang Ding : %llu\n", ULLONG_MAX );
    
    return 0;
    }
    

    Output:

    unsigned char : 3
    unsigned short int : 5
    unsigned int : 10
    unsigned long : 20
    unsigned long long : 20
              Ding : 4294967295
         Lang Ding : 18446744073709551615
    Heel lang Ding : 18446744073709551615