Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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.

like image 963
helpermethod Avatar asked Nov 30 '10 20:11

helpermethod


2 Answers

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.

like image 140
Yakov Galka Avatar answered Nov 16 '22 23:11

Yakov Galka


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.

like image 42
T.E.D. Avatar answered Nov 16 '22 23:11

T.E.D.