Varun Shaandhesh
Varun Shaandhesh

Reputation: 79

Printing a character data type as integer data type

#include<stdio.h>
main()
{
    char a[12];
    scanf("%s",a);
    int s=0;
    s=s+a[1];
    printf("%d",s);
}
example:
a=1234
output:50

This is a basic c program.When i try to print the value of s,it displays 50 but when i replace a[1] with a[1]-'0',it displays the exact value of character present at the index(output: 2).Any reason why is it happening ?

Upvotes: 0

Views: 50

Answers (3)

chux
chux

Reputation: 153508

C specifies that the codes for characters '0', '1', '2', ... '9' are sequential.
'0' + 3 must equal '3'.
This applies for any character set: the common ASCII or others.

Subtraction from '0' yields the numeric difference.

printf("%d",'2' - '0'); // must print 2

... the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous. ... C11dr §5.2.1 3

Upvotes: 0

asio_guy
asio_guy

Reputation: 3767

lets take a look what happened at run time.

s is initialized to 0

and a[] is scanned with "1234"; 

which is

a[0] = '1';
a[1] = '2';
a[2] = '3';
a[3] = '4';

first case

s=s+a[1]; // 0 + asci value of 2 which evaluates to 50

second case

s=s+a[1]-'0' //  0 + asci value of 2 i.e 50 - asci value of 0 i.e 48 = 2

man -a ascii

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

Character constant '2' in the ASCII table has code 50. So using the format specifier %d the character is displayed as an integer that is its value 50 is displayed.

As for this expression

a[1] - '0'

then as it has been said a[1] that represents the character '2' stores the ASCII value 50. The character '0' has the ASCII code 48. So the difference yieds 2.

Upvotes: 1

Related Questions