while(*s++); 和 while(*s)s++; 的区别?

《C程序设计语言》第二版的习题5.1:用指针的方式实现strcat即字符串连接函数。

这个是可以实现的

#include <stdio.h>

void strcatp(char *s, char *t);

int main()
{
	char s[] = "Hello";
	char t[] = " world!";
	
	strcatp(s, t);

    printf(s);
	return 0;
}

void strcatp(char *s, char *t){
    while(*s)
        s++;
    
    while(*s++ = *t++)
    	;
}

输出结果为Hello world!

而这种却不行?

#include <stdio.h>

void strcatp(char *s, char *t);

int main()
{
	char s[] = "Hello";
	char t[] = " world!";
	
	strcatp(s, t);

    printf(s);
	return 0;
}

void strcatp(char *s, char *t){
    while(*s++)
        ;
    
    while(*s++ = *t++)
    	;
}

输出结果:Hello

阅读 7.5k
3 个回答

关键的错误是

    while(*s)
        s++;

在s指向\0时候停止增加指针。

    while(*s++)
        ;

在指向\0时候仍为指针增加了1。从而使得两段拼接的字符串中间存在\0,printf在这个中间点认为字符串已经结束。

while (*s++);

等于

while (true) { char c = *s; s++; if (!c) break; }

while (*s) s++;

等于

while (true) { char c = *s; if (!c) break; s++; }

答案楼上已经说的很详细了,我说下我的看法。
首先,lz做靠谱书的课后题是没错的。
对语言了解一些之后,最好是找一些几百行代码的项目来读。

我不建议学习某种语言纠结于诸如运算符优先级这种细节。不太清楚优先级的时候,上() 就可以了。在写代码的过程中,理清逻辑更重要。

(拙见,求喷)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进