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?
>Solution :
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
aof one type but tellprintfto expect another type.printffetches 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 ofaas the new type. - You pass a variable
aof one type but tellprintfto expect another type. However, the rules for passing these types say to pass them in different places.amight be passed in a general processing register, but the other type might be passed in a floating-point register. Soprintffetches the bytes from where it expects them to be, but the bytes ofaare not there. Instead,printfgets 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.