Learn C: Variables and Operators. VARIABLES: LESSON Casting Types Continued

https://www.codecademy.com/courses/learn-c-variables-and-operators/lessons/variables-c/exercises/casting-types-continued

//I have a silly question :) //I understand this line: targetChar = (char)sourceInt; /*that targetChar wasn't declared and has no value in it unless we cast the sourceInt with a (char). But what I do not understand is that why do we not have to do the same for the very next line:*/ targetChar = sourceDouble; /*Why do we not have to add a cast (char) with the sourceDouble? And what is the difference between */ targetChar = sourceDouble; //and, targetChar = (char)sourceDouble; /*They both give us 7 anyway, but I do not understand why.*/

It’s an implicit cast. In my opinion, these are quirks. Aim to be as explicit and predictable as possible. And especially with C and C++, just because the compiler doesn’t throw an error, doesn’t mean that certain behavior is defined (and therefore you don’t know how different compilers/architectures will treat it).

1 Like