33,321
社区成员




#include <stdio.h>
/*实现字符串的逆置,用键盘输入字符串,并输出逆置前后的字符串(用函数实现逆置,指针变量作为形参*/
void fun(char *p)
{
int n=0;
while(*p++)
{
n++;
}
p-=2;
while(n--)
{
printf("%c",*p--);
}
}
int main()
{
char str[100]={0};
gets(str);
fun(str);
return 0;
}
1234567890
0987654321Press any key to continue
不要使用
while (条件)
更不要使用
while (组合条件)
要使用
while (1) {
if (条件1) break;
//...
if (条件2) continue;
//...
if (条件3) return;
//...
}
因为前两种写法在语言表达意思的层面上有二义性,只有第三种才忠实反映了程序流的实际情况。
典型如:
下面两段的语义都是当文件未结束时读字符
while (!feof(f)) {
a=fgetc(f);
//...
b=fgetc(f);//可能此时已经feof了!
//...
}
而这样写就没有问题:
while (1) {
a=fgetc(f);
if (feof(f)) break;
//...
b=fgetc(f);
if (feof(f)) break;
//...
}
类似的例子还可以举很多。