当我在 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));
所以我们有未定义的行为。在这种情况下,编译器所做的是在 toupper(*beg)
之前评估 beg++
在 C 中,而在 C++ 中它以另一种方式进行。
关于c++ - 在 C 和 C++ 中将 C 字符串转换为大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33086007/