printf(%d) printing a very big integer

44 views Asked by At

I did this simple function to print the content of an array of int.

void print_array(int size, int array[size])
{
    printf("{");
    for (int i = 0; i < size - 1; i++)
    {
        printf("%d, ", array[i]);
    }
    printf("%d}\n", array[size - 1]);
}

It seems to work fine with examples. However, while using it to debug a function, I got the result :

{-1, 0, 1, 2, 3, 4, 16, 17, 18, 8, 0, 1, 11, 12, 13, 14, 15, 27, 28, 9, 30, 31, 21, 24, 14, 24, 25, 26, 27, 19, 31, 41, 33, 23, 33, 34, 35, 27, 28, 29, 50, 808779818, -363075840, -202888522, 45, 46, 0, 0, -1377617600, 32767, -1377617208, 32767, 2055390135, 22066, 2055404888, 22066, 448540736, 32670, 446392223, 32670, 16, 48, -1377617632, 32767, -1377617824, 32767, -363075840, -202888522, 448540736, 32670, 32670, 0, 284, 0, 1, 0, 0, 0, -1377617929, 32767}

As you can see, some of the numbers here are too big to be printed as int, even though I used the %d identifier in the printf function. Can someone explain to me what happens here ? When I'm testing the equality of this array with the good answer, the test happen to be true (???).

I tried understanding it by doing

    int a = 808779818;
    int b = 42;
    assert(a == b);

but there the assert fails.

1

There are 1 answers

0
gulpr On

As you can see, some of the numbers here are too big to be printed as int

You can easily check what is maximum and minimum integer value in your system:

int main(void)
{
    printf("int: %d  %d\n", INT_MIN, INT_MAX);
    printf("short int: %hd  %hd\n", SHRT_MIN, SHRT_MAX);
    printf("char: %hhd  %hhd\n", CHAR_MIN, CHAR_MAX);
    printf("long int: %ld  %ld\n", LONG_MIN, LONG_MAX);
    printf("long long int: %lld  %lld\n", LLONG_MIN, LLONG_MAX);
}

https://godbolt.org/z/az7nd8fEP

int a = 808779818;
int b = 42;
assert(a == b);

From man pages:

   If expression is false (i.e., compares equal to zero), assert()
   prints an error message to standard error and terminates the
   program by calling abort(3).  The error message includes the name
   of the file and function containing the assert() call, the source
   code line number of the call, and the text of the argument;
   something like:

but there the assert fails.

And it is expected result as 808779818 != 42