为什么 char 在 C++ 中不被视为数字?
我用 C 编写了一段代码,运行良好,我将它翻译成 C++.那里给出了错误的输出.我进行了一次迭代,其中我将输入和迭代器变量都用作 char 以节省空间.但表现不如预期.
I wrote a code in C, which ran perfectly, I translated it to C++ . There it was giving wrong output. I had an iteration where I used both the input and the iterator variable as char to save space. But didn't behaved as expected.
unsigned char repeat, i;
cin >> repeat;
for(i= 0; i < repeat; i++)
等价线是什么
scanf("%hhi", &repeat)
?
推荐答案
为什么 char 在 C++ 中不被视为数字?
Why char is not taken as numeral in C++?
因为 C 和 C++ 是不同的编程语言.
参见例如 n3337,C++ 标准草案,实际上等同于 C++11 标准.对于 C11 编程语言,请查看 n1570 和 CompCert 项目.
Because C and C++ are different programming languages.
See for example n3337, a draft C++ standard, practically equivalent to C++11 standard. For the C11 programming language, look into n1570 and the CompCert project.
编程语言是一种规范,通常写在一些文档中.它的 语义 和它的 语法.
A programming language is a specification, usually written in some documentation. Its semantics matters as much as its syntax.
如果您使用 GCC 的一些最新变体编译 C++ 源代码,我建议您使用 invoke 它为 g++ -Wall -Wextra -g
即启用大量警告和一些调试信息.
If you compile your C++ source code with some recent variant of GCC, I suggest to invoke it as g++ -Wall -Wextra -g
that is to enable a lot of warnings and some debug info.
考虑同时使用一些静态程序分析工具,例如Frama-C 或 Clang 静态分析器 或 Coverity 等......
Consider also using some static program analysis tools, e.g. Frama-C or Clang static analyzer or Coverity etc....
另请阅读如何调试小程序 以及关于 未定义的行为
另请参阅有关 C 和 C++ 的网站 并查看 RefPerSys(一些有趣的"C++ 自由软件 项目,AGI 相关).
Refer also to this site about C and C++ and look into RefPerSys (some "interesting" C++ free software project to which I actively contribute, AGI related).
研究现有 C++ 开源项目的源代码,至少是为了获得灵感.Qt 或 鱼壳 立即浮现在脑海(但在 github 或 gitlab 或其他地方,例如 Ghudi, PPL, Fox 工具包,FLTK).通过积极参与其中之一,您将学到很多东西(甚至可能是 RefPerSys)
Study, at least for inspiration, the source code of existing C++ open source projects. Qt or the fish shell comes immediately to mind (but thousands of others exist on github or on gitlab or elsewhere, e.g. Ghudi, PPL, Fox toolkit, FLTK). You'll learn a lot by actively contributing to one of them (perhaps even RefPerSys)
顺便说一句,我强烈建议显式在 C 或 C++ 中初始化每个数字变量(因此代码 unsigned char repeat=0, i=0;
在您的情况下).任何足够好的 优化编译器 都会在它们无用时删除它们,并调试您的程序(例如,使用 gdb
,特别是在 GNU/Linux 系统,例如 Ubuntu 或 Debian) 的行为变得更具确定性时会更容易.
BTW, I strongly recommend explicitly initializing every numeric variable in C or in C++ (so code unsigned char repeat=0, i=0;
in your case). Any good enough optimizing compiler would remove them when they are useless, and debugging your program (e.g. with gdb
, notably on GNU/Linux systems such as Ubuntu or Debian) would be easier when its behavior becomes more deterministic.
相关文章