jeudi 9 juin 2016

Why the following code does print "S is Bigger" even though s is smaller?

Following snippet of code is not working as I expected, the output of the following program is "S is Bigger" when compiled with GCC in an Ubuntu machine. Although the variable s is -1 and which is clearly smaller than sizeof(buffer) which is 20. But still it prints S is Bigger.

Only logical assumption I can make is that C is converting the variable "s" to unsigned integer and using in "If" condition. If My assumption is correct why C is doing that or if I am wrong why this snippet is giving this confusing output.

#include <stdio.h>

int main(void) {

    int s = -1;
    char buffer[20];

    if(s > sizeof(buffer)){
        printf("S is Bigger");
    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire