与负整数比较时忽略 for 循环条件

for-loop condition ignored when comparing to negative integer

在编写一个函数来计算字符串 sub 在字符串 s 中出现的位置时,我发现当使用空字符串作为 s.

char* s = "";
char* sub = "up";

for(int i = 0; i <= (strlen(s) - strlen(sub)); i++){

    //stuff
}

在这种情况下,循环继续进行,就好像不满足条件一样。

但是,如果我以这种方式重写条件,它会按预期工作。

int max = strlen(s) - strlen(sub);

for(int i = 0; i <= max; i++){

   //stuff
}

所以我想知道是什么导致了这种行为。

在for循环的条件下

for(int i = 0; i <= (strlen(s) - strlen(sub)); i++){

    //stuff
}

表达式 strlen( s )strlen( sub ) 都具有无符号整数类型 size_t。所以表达式strlen(s) - strlen(sub)也不能为负数。

因为strlen( sub )大于strlen( s )那么它们的差值会产生一个非常大的size_t.

类型的值

尝试调用 printf

printf( "size_t( -2 ) = %zu\n", size_t( -2 ) );

它在某些系统中的输出可以是例如下面的

size_t( -2 ) = 4294967294

而在同一系统中 INT_MAX 的值等于 2147483647

而且INT_MAX的值小于上面表达式得到的值,那么你可以得到一个无限循环。

你需要的是按以下方式重写条件

for ( size_t i = 0; i  + strlen( sub ) <= strlen(s); i++){

    //stuff
}