edited by
1,355 views
3 votes
3 votes
#include<stdio.h>
int main()
{
    char c = 125;
    c = c+10;
    printf("%d", c);
    return 0;
}



what will be the output , explain with logic(size of char 1 byte)

edited by

2 Answers

Best answer
5 votes
5 votes
char takes 1 byte. But when given to a function, these are promoted to int. So, positive char values are padded with 0s on the left and negatives ones with 1s (sign extension).

The maximum value which can be stored in a char is 127 if it is signed. Whether by default a char is signed or unsigned is "implementation defined" and lets assume signed here. Now, when we add 10, this becomes 135 which overflows and hence becomes 135-256 = -121 (2's complement representation). Now, if this is printed using %d, we get -121. If we use %u, we get UINT_MAX - 135.
edited by
3 votes
3 votes

C = 0111 1101  (125)
C = C + 10;
C = 1000 0111 (135)

%d is format specifier for signed integers which treats numbers in 2's complement form.
2's complement of 1000 0111 will be 0111 1001 = -121 

Hence O/P will be -121.

Related questions

1 votes
1 votes
3 answers
2
shiva0 asked Apr 3, 2019
468 views
What is the output of the program? int main() { union a { int i; char ch ; }; union a u; u.ch[0] = 3; u.ch = 2; printf("%d, %d, %d", u.ch[0], u.ch , u.i); return 0; }
1 votes
1 votes
1 answer
3
srestha asked Aug 8, 2018
580 views
#include <stdio.h int main() { long int a = 0x7fffffff * 0x7fffffff; long int b = 0x7fffffff * 0x7fffffffl; printf("a = %ld, b = %ld\n", a, b); return 0; }What will be ou...
0 votes
0 votes
1 answer
4
radha gogia asked Aug 10, 2015
398 views
CASE A: CASE A: &#8234;#&lrm;include&#8236;<stdio.h int divide( int a, b) { return 7; } int main() { int a=divide(8,3); printf("%d",a); return 0; }CASE B :CASE B : #inclu...