c - 短 C 代码 : Confused strlen() function

标签 c

我的编译器:Dev C++ 5.3.0.3 TDM-GCC 4.6.1 64 位 我的操作系统:Windows 7,64 位

我的 C 代码:

# include "stdio.h"
# include "string.h"

# define MAX (501)

int main() {
    char
        text[MAX]="";

    int i;

    i=0;
    printf("%d\n",strlen(text));        /* 0 */
    printf("%d\n",(strlen(text)-1));    /* -1 */
    if ( i<= (strlen(text)-1) ) printf("haha"); /* haha */

    return 0;
}

我的问题:为什么打印“haha”?!(0>-1?!!!) 感谢您的帮助!

最佳答案

strlen返回一个 unsigned 值,比较 i < strlen(text) - 1无符号整数执行,其中0确实不比另一个大。

在处理无符号类型时,如果只使用 + 会容易得多。 :

if (i + 1 <= strlen(text))

或者更好:

if (i < strlen(text))

理解内置类型和运算符的算术提升和转换可能有点棘手,但可能值得一读。肯定有一些意想不到的情况。一个好的编译器可以在你 comparing signed with unsigned types 时警告你.

(如果您好奇为什么同时具有有符号和无符号类型的表达式都被提升为无符号,您可能会注意到从有符号到无符号的转换是绝对明确定义的(通过模运算),而从无符号的转换to signed 是实现定义的。我想这意味着提升规则意味着算术运算和比较的行为是明确定义的,而不仅仅是实现定义的。)

关于c - 短 C 代码 : Confused strlen() function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14674825/

相关文章:

c - 编译期间出现 fatal error 消息

c - 检测文本文件结尾,使用 fgetc 读取

c - c中scanf函数的功能

c - 为什么我在这个程序中使用指针时会得到垃圾? C语言

c - 序列点和副作用

C 从文本文件中读取负整数

c - 为什么说 "expression is not assignable"?

c++ - 检测usb设备的API

代码执行无法继续,因为找不到 libquickmail-0.dll?

c - 将数据结构保存到文本文件