开发者

C++ Assigning an int to a char - why does this work without at least a warning?

开发者 https://www.devze.com 2023-01-27 21:43 出处:网络
Why does C++ (and probably C as well) allow me to assign and int to a char without at least giving me a warning?

Why does C++ (and probably C as well) allow me to assign and int to a char without at least giving me a warning?

Is it okay to directly assign the value, like in

int i = 12;
char c = i;

i.开发者_开发问答e. do an implicit conversion, or shall I use a static_cast<>?

EDIT

Btw, I'm using gcc.


It was allowed in C before an explicit cast syntax was invented. Then it remained a common practice, so C++ inherited it in order to not break a huge amount of code.

Actually most compilers issue a warning. If your doesn't, try change its settings.


C as originally designed wasn't really a strongly-typed language. The general philosophy was that you the programmer must know what you are doing, and the compiler is just there to help you do it. If you asked to convert between float, int, and unsigned char six or seven times in a single expression, well that must be what you wanted.

C++ sort of picked that up just so that all the existing C code wouldn't be too much of a bear to port. They are slowly trying to make it stronger with each revision though. Today just about any C++ compiler will give you a warning for that if you turn the warning levels up (which I highly recommend you do).

Otherwise, perhaps you should look into true strongly-typed languages, like Java and Ada. The equivalent Ada code would not compile without an explicit conversion.


Short answer: It's okay (by the c++ standard) in your example.
Slightly longer answer: It's not okay if char is signed and you are trying to assign it a value outside its range. It's okay if it is unsigned though (whether or not char is signed depends on your environment), then you'll get modulo arithmetics. Compilers usually have a switch to warn you because of the first case, but as long as you stay in the bounds it's perfectly fine (however, an explicit cast to make your intentions clear does not hurt).


char is the same as short. So, there should be a warning about possible lose of information. May be you have warnings switched off, try to configure somehow your compiler/ide.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号