In a C book says that char data type can memorise numbers and ascii characters. How the computer knows if I refer to a character or to a number? For example, if I want to print on screen the value of a char variable, how computer knows if I refer to the ascii character for that number or I refer to that number?
Thanks in advance.
The compiler doesn't necessarily handle this automatically. In C, this is handled in console output via format specifiers.
printf("This is a char:%c\n", 'c');
printf("This is an int:%d\n", 3);
If you provide the wrong data type as the argument corresponding to the format specifier in your format string, you will get compiler warnings:
printf("This is a char:%c\n", 1); // WARNING: Implicit conversion from (int) to (char) (due to implicit down-cast)
You may not get such a compiler warning depending on the verbosity level if you provide an argument that is smaller than what was expected, ie:
printf("This is an int:%d\n", 'b'); // Implicit up-cast
So, in short, the format specifier lets the compiler know how to represent the data when it comes to printing it to the console, and will also do type-checking between the format specifiers and the corresponding arguments if there is a mismatch.
Finally, if your compiler is C99 compliant, printf will convert an integer to its character-literal equivalent if you have a type-mismatch:
printf("This is a char:%c\n", 99); // Prints the 'c' character literal
You can find the character/number mappings here:
http://www.asciitable.com/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With