If i cast a variable type called "a" to another variable type called "b", "b" now is "a" interpreted as the new variable type. And if I have one variable type called "a" and I printf it with another variable type, the output will be "a" interpreted as the new variable type. So is printf making a hidden casting process to do that?
CodePudding user response:
If i cast a variable type called "a" to another variable type called "b", "b" now is "a" interpreted as the new variable type.
No, a cast converts a value to another type; it does not reinterpret a variable. If a
is an int
with value 3, then (float) a
is a float
with the same value, 3.
And if I have one variable type called "a" and I printf it with another variable type, the output will be "a" interpreted as the new variable type. So is printf making a hidden casting process to do that?
Answering the second question first, no, printf
is not doing any casting in this case. Regarding the first question, that is the output that may appear in some cases. But the behavior is not defined by the C standard. Some of the things that may happen include:
- You pass a variable
a
of one type but tellprintf
to expect another type.printf
fetches the bytes of the argument from where you put the bytes ofa
, but, because it expects a different type, it interprets the bytes as if they were encoded using the rules for the other type, so it reinterprets the bytes ofa
as the new type. - You pass a variable
a
of one type but tellprintf
to expect another type. However, the rules for passing these types say to pass them in different places.a
might be passed in a general processing register, but the other type might be passed in a floating-point register. Soprintf
fetches the bytes from where it expects them to be, but the bytes ofa
are not there. Instead,printf
gets some other bytes that happened to be in the register and converts those for printing. - The argument passing fails in other ways and corrupts your program.
- The compiler catches the error during compilation and either warns you or refuses to compile your program, depending on settings.