dimanche 27 décembre 2015

Why (positive_integer < negative_integer) is getting evaluated to be true in C?

$ gcc --version  
gcc (Debian 4.9.2-10) 4.9.2

In the following code snippet why is the expression 100 < strlen(str) - 4 getting evaluated as true?

#include <stdio.h>
#include <string.h>

int main(void)
{
    char str[50];

    scanf("%s", str);
    printf("%d\n", strlen(str) - 4);

    if(100 < (strlen(str) - 4))
        printf("NOT POSSIBLE!\n");

    return 0;
}

Terminal:

$ gcc so.c -o so  
$ ./so  
foo
-1
NOT POSSIBLE!  

From experimenting a bit I found out :

  1. the if expression evaluates to true for any positive_int, negative_int pair such that positive_int < negative_num (which is absurd) where negative_int is in the form of strlen function call (see 2.)
  2. if we replace the strlen with a hard coded negative integer then if evaluates to false as expected. Looks like there's something wrong with strlen.

Aucun commentaire:

Enregistrer un commentaire