0

I didn't touch C for a while and now I am surprised that this while-loop is more mystic than I ever realized.

I tried while ((byte_sent < sizeof(int))) and while (byte_sent < sizeof(int)), the same result I got. The code inside the loop is never reached.

Tested with Gcc, Clion build chain, online compiler.

#include <stdio.h>

int main()
{
    int byte_sent = -1;
    while ((byte_sent < sizeof(int))) {
        printf("We are in\n");
        break;  // Just want to know if the inner loop gets executed
    }
    return 0;
}

Que0Le
  • 84
  • 5

2 Answers2

3

Try compiling with -Weverything(clang):

c.c:6:23: warning: comparison of integers of different signs: 'int' and 'unsigned long' [-Wsign-compare]
    while ((byte_sent < sizeof(int))) {
            ~~~~~~~~~ ^ ~~~~~~~~~~~
1 warning generated.

sizeof returns an size_t (Here a typedef for unsigned long), byte_sent is an int.

The integer is casted to size_t. So byte_sent is now 4294967295, as size_t(unsignd long) has no negative numbers.

JCWasmx86
  • 3,473
  • 2
  • 11
  • 29
1

You need to cast sizeof(int) to an int: (int)sizeof(int), or it will automatically cast byet_sent to a size_t which is an unsigned long.

Edit: Look at JCWasmx86's answer for more detailed explanation!