Lev*_*glu 0 c increment while-loop post-increment postfix-operator
我为Brian Kernighan的" The C Programming Language " 练习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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我在while循环中使用postfix increment(++)运算符,则函数会失败;
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;
}
}
Run Code Online (Sandbox Code Playgroud)
唯一的区别是,我使用了一个postfix ++运算符,而不是在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;
}
}
*/
Run Code Online (Sandbox Code Playgroud)
后缀增量运算符返回原始值并递增1.
while( src[len] != '\0')
len++;
Run Code Online (Sandbox Code Playgroud)
在工作版本中,while循环将在src[len]a 时终止\0.当while循环测试条件失败时,循环内的语句不会执行.循环后len包含一个值src[len] == '\0'.
while (src[len++] != '\0');
Run Code Online (Sandbox Code Playgroud)
在您的修改版本中,当执行最终测试时len将再增加一次.在循环len包含src[len]一个超过数组末尾的值之后.
但是,for循环假设这len是字符串长度,因此您有一个一个一个错误.