一般来说,我知道您为什么会收到此错误,但在这个特定实例中我有点困惑...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* mystrncpy(char* dst, const char* src, size_t n) {
char* temp = dst;
while (n-- > 0 && (*temp = *src)) {
temp++;
src++;
}
return dst;
}
int main() {
const char* str = "Hello World!";
char buf[50];
memset(buf, 0, sizeof(buf));
mystrncpy(buf, str, sizeof(buf));
printf("%s\n", buf);
}
上面的代码效果很好,但是如果我删除额外的一组括号,将 while 循环更改为:
while (n-- > 0 && *temp = *src)
然后我得到了错误。我想这与运算符优先级有关,但我有点困惑。有人可以解释一下 while 循环更改是如何导致出现此编译器错误的吗?
最佳答案
是的,这是关于优先级的。
=
的优先级低于 &&
。因此,后一种情况解析为:
while ((n-- > 0 && *temp) = *src)
当然 (n--> 0 && *temp)
不是左值。
您确定您不打算使用 ==
而不是 =
吗?
关于c - 左值需要作为赋值错误的左操作数——但为什么呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8884665/