Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char data type in C

Tags:

c

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.

like image 632
user2956608 Avatar asked Jul 03 '26 13:07

user2956608


1 Answers

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/

like image 170
Cloud Avatar answered Jul 05 '26 04:07

Cloud