R
Richard Bos
somenath said:In page number of 154 in K&R2 in Table 7-1 it is stated that
Characters Argument Type : Printed As
d,i int, decimal number
c int; single character
Now suppose for the following code
#include<stdio.h>
int main(void)
{
printf("%c", '1'+ 1);
return 0;
}
The output of the program is 2 .
Because the integer value of '1' is 49 so 49+1 =50 ,character
equivalent of decimal 50 is 2 .
Almost. The absolute values 49 and 50 for '1' and '2' are not guaranteed
(because the Standard doesn't require ASCII), but ISO C _does_ demand
that '2' immediately follows '1'.
But my doubt is
Question. Your _question_ is.
The type of the expression '1' + 1 is integer. So if I use %c to
print the integer will it show undefined behavior?
From the ISO C Standard (1989, as it happens, but C99 is the same):
# 4.9.6.1 The fprintf function
....
# c The int argument is converted to an unsigned char, and the
# resulting character is written.
Note: _int_ argument, which is converted to an unsigned char. So no, as
you thought, it does not have undefined behaviour.
Richard