c - Postfix++ 运算符在 While 条件下未按预期运行

标签 c while-loop increment post-increment postfix-operator

我已经为 Brian Kernighan 的“The C Programming LanguageExercise 1-19 编写了一个简单的解决方案,反转字符串的。 reverse(char[]) 函数如下,一切正常;

void reverse(char src[])
{   
    int len = 0;
    while( src[len] != '\0')
        len++;

    for(int i = 0; i < len/2; i++)
    {
        char temp = src[i];
        src[i] = src[len - 1 - i];
        src[len - 1 - i] = temp;
    }
}

但是,如果我在 while 循环中使用后缀增量 (++) 运算符,函数将失败;

void reverse(char src[])
{   
    int len = 0;
    while( src[len++] != '\0')      // this fails
        ;

    for(int i = 0; i < len/2; i++)
    {
        char temp = src[i];
        src[i] = src[len - 1 - i];
        src[len - 1 - i] = temp;
    }
}

唯一的区别是,我没有在 while 循环中递增变量 len,而是使用了一个后缀++ 运算符,行为期望应该是这样的,“使用旧值进行条件检查,在完成递增后”。

为什么它没有按预期工作,我哪里做错了?我在 Windows 10 Mingw/gcc 编译器下编译它。这是完整的测试代码;

测试代码

#include <stdio.h>

#define STR_NUM     5
#define STR_SIZE    20

void reverse(char[]);   // declaration

int main()
{   
    char str[STR_NUM][STR_SIZE] =
    {
        { "A"     },
        { "AB"    },
        { "ABC"   },
        { "ABCD"  },
        { "ABCDE" }
    };

    for(int i = 0; i < STR_NUM; i++)
        reverse(str[i]);

    for(int i = 0; i < STR_NUM; i++)
        printf("%s\n", str[i]);

    return 0;
}

// this is working
void reverse(char src[])
{   
    int len = 0;
    while( src[len] != '\0')
        len++;

    for(int i = 0; i < len/2; i++)
    {
        char temp = src[i];
        src[i] = src[len - 1 - i];
        src[len - 1 - i] = temp;
    }
}

// this is failing
/*
void reverse(char src[])
{   
    int len = 0;
    while( src[len++] != '\0')      // this fails
        ;

    for(int i = 0; i < len/2; i++)
    {
        char temp = src[i];
        src[i] = src[len - 1 - i];
        src[len - 1 - i] = temp;
    }
}
*/

最佳答案

后缀递增运算符返回原始值并递增 1。

while( src[len] != '\0')
    len++;

在工作版本中,当 src[len]\0 时,while 循环将终止。当 while 循环测试条件失败时,循环内的语句不执行。在循环 len 包含一个值使得 src[len] == '\0' 之后。

while (src[len++] != '\0');

在您的修改版本中,当执行最终测试时,len 将增加一次。在循环之后 len 包含一个值使得 src[len] 是数组末尾之后的一个值。

然而,for 循环假定 len 是字符串长度,因此您会遇到一个差一错误。

关于c - Postfix++ 运算符在 While 条件下未按预期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36633353/

相关文章:

MySQL触发器增加/减少其他表中的值

c - 如何通过我的函数将 "..."(可变长度 arg 列表)不变地传递给另一个函数?

c - 如何使用 while 语句使用 while 循环求平方根

c - 试图了解位 ram 地址

Java:不退出 while 循环?

c++ - 应用程序菜单中显示的错误

php - do-while/while 中的分配没有按预期工作

c - 服务器中的父进程卡在接受调用中。我如何从 child 那里干净地终止 parent

processing - 处理中三个椭圆的轮播

Powershell 一次递归 move 20,000 个文件