今天我试图调试一个应用程序,我发现了一个包含strlen()的布尔表达式的奇怪行为.
下面是一个简单的代码,可以重现该问题.
char test[20] = "testTestTest"; //the length is 12
bool b = 0 < (9 - strlen(test)); //should be false (0 < -3) = false
Run Code Online (Sandbox Code Playgroud)
在执行结束时b是真的,但它应该是假的.
将strlen()的结果保存在变量中.
char test[20] = "testTestTest"; //the length is 12
int length = strlen(test); //save the length
bool b = 0 < (9 - length); //should be false (0 < -3) = false
Run Code Online (Sandbox Code Playgroud)
在执行结束时b是假的(因为它应该是).
这两种实现有什么区别?
为什么第一个不起作用?
原始受影响的代码是这样的:
char test[20] = "testTestTest"; //the length is 12
for(int i = 0; i < (9 - strlen(test)); …Run Code Online (Sandbox Code Playgroud)