Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is casting the same as interpreting in printf(c)

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 tell printf to expect another type. printf fetches the bytes of the argument from where you put the bytes of a, 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 of a as the new type.
  • You pass a variable a of one type but tell printf 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. So printf fetches the bytes from where it expects them to be, but the bytes of a 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.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading