Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof() behaviour in C programming

This is my program..

int main(void) {

    printf("%lu\n", sizeof(""));

    // first if else statement
    if(1 > -2) printf("Yes");
    else printf("No");

    printf("\n");

    // second if else statement    
    if( sizeof("") > -2) printf("Yes");
    else printf("No");
}

In first printf() why it's printing 1 as output,though I've passed an empty string? In first if-else statement I got the correct output -> Yes as expected, but in second if-else statement It prints the outout -> No, Can anyone explain me why this is happening?

My output is.. 1 Yes No

Thanks in advance :-)

like image 833
santhosh136 Avatar asked Dec 14 '22 08:12

santhosh136


1 Answers

sizeof("") is one because string literals represent character arrays that contain the given characters followed by '\0'. So "" represents the character array {'\0'}.

sizeof("") > -2 is false because sizeof returns a size_t, which is an unsigned integer type. The comparison causes -2 to be converted to size_t, which causes it to wrap around and become a number much larger than one.

like image 65
sepp2k Avatar answered Dec 23 '22 09:12

sepp2k