Why char is not taken as numeral in C++?

大憨熊 提交于 2020-06-08 19:44:09

问题


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++)

What is the equivalent line for

scanf("%hhi", &repeat)

?


回答1:


Why char is not taken as numeral in C++?

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.

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.

Consider also using some static program analysis tools, e.g. Frama-C or Clang static analyzer or Coverity etc....

Read also How to debug small programs and about Undefined behavior

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).

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)

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.



来源:https://stackoverflow.com/questions/61228466/why-char-is-not-taken-as-numeral-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!