user2956608
user2956608

Reputation: 69

char data type in 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.

Upvotes: 3

Views: 2247

Answers (3)

Joe DF
Joe DF

Reputation: 5558

According to "The C Programming Language", 2nd Edition,
Section A4.2 "Meaning of Identifiers" : "Basic Types", Page 195

Objects declared as characters (char) are large enough to store any member of the execution character set. If a genuine character from that set is stored in a char object, its value is equivalent to the integer code for the character, and is non-negative.

and therefore, the following works (if the character set is ASCII, i.e. The following example is for ASCII)

int n = 65; //is equal to 'A' in ASCII
char c = 'A'; //is equal to 65 in ASCII
printf("%c %d", n, c); //should print "A 65" despite the "wrong" order

According to Page 244, "Standard Library", "Formatted Output", "printf functions"
For the '%c' format specifier, printf does the following: convert int to unsigned char

int; single character, after conversion to unsigned char.

Upvotes: 2

Cloud
Cloud

Reputation: 19331

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/

Upvotes: 3

SHR
SHR

Reputation: 8333

you give format to printf()

if you use:

char c = 'c';
printf("%c \n", c); //result is the character 'c'.
printf("%d \n", c); //result is 99, the ASCII value of character 'c'.

but note never to use format %d for char in scanf, this may destroy your stack.

scanf("%d \n", &c); //NEVER do this.

Upvotes: 1

Related Questions