Home > Back-end >  Variable is correct, but test case does not execute
Variable is correct, but test case does not execute

Time:11-13

I wrote the following code:

#include <stdio.h>

int array[] = {23, 43, 12, 17, 204, 99, 16};
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))

int main()
{
        int test = -1;

        if (test <= TOTAL_ELEMENTS)
        {
                printf("Hello, got here!\n");
        }
}

When I compile this code (with gcc main.c -Wall (no warnings!)), and run it, the printf fails to execute. I mean, test = -1, and that is definitely smaller than the size of the array (7 digits). Where is the bug?

CodePudding user response:

The bug was in the difference between unsigned and signed. Specifically, the defined variable TOTAL_ELEMENTS's type is unsigned int (sizeof returns unsigned because a size can never be negative). The test is comparing a signed int with an unsigned int. That fails because test is promoted to unsigned. -1 turned into unsigned becomes a large positive integer, thus making the if conditional return false.

If you compile with gcc main.c -Wall -Wextra it will warn.

  • Related