当我在C++中组合一个大写函数时,我注意到我没有在C中收到预期的输出。
C++函数
#include <iostream>
#include <cctype>
#include <cstdio>
void strupp(char* beg)
{
while (*beg++ = std::toupper(*beg));
}
int main(int charc, char* argv[])
{
char a[] = "foobar";
strupp(a);
printf("%s\n", a);
return 0;
}
预期输出:
FOOBAR
C函数
#include <ctype.h>
#include <stdio.h>
#include <string.h>
void strupp(char* beg)
{
while (*beg++ = toupper(*beg));
}
int main(int charc, char* argv[])
{
char a[] = "foobar";
strupp(a);
printf("%s\n", a);
return 0;
}
输出是预期结果,缺少第一个字符
OOBAR
有谁知道为什么在C语言中编译时结果会被截断?
最佳答案
问题是在其中没有序列点
while (*beg++ = toupper(*beg));
因此,我们有未定义的行为。在这种情况下,编译器要做的是先评估
beg++
,然后再评估toupper(*beg)
。在C语言中,C语言采用另一种方式。关于c++ - C字符串在C和C++中为大写,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33086007/