why is the output of this question is 266 -1 10 in turbo c compiler?

61 Views Asked by At
int main(){
    int a, b;
    char *cp;
    a = 511;
    cp = &a;
    b = *cp;
    *cp = 10;
    printf("%d %d %d", a,b,*cp);
    return 0;
}

The output for the above code is 266 -1 10 I understood how a = 266, this is because the first byte of a is replaced with the binary eqivalent of 10(*cp = 10) that makes a = 0000 0001 0000 1010 . But I am not able to understand why b is -1. In the line b = *cp, *cp in binary is 1111 1111 and this is copied to b, but why the end value is -1?

1

There are 1 best solutions below

0
Vlad from Moscow On

To understanf the output try this simple demonstration program.

#include <stdio.h>

int main( void )
{
    int a = 511;
    char c = -1;

    printf( "a = %#x, c = %#x\n", a, ( unsigned char )c );
}

Its output is

a = 0x1ff, c = 0xff

It seems the pointer cp assigned like

cp = &a;

points to the less significant byte of the onbject a that contains the value 0xff.

Also it seems that the type char behaves as the type signed char in the compiled program. In this case the value 0xff interpreted as a value of an object of the type char internally represents the value -1. And this value is assigned to the variable b

b = *cp;

So the variable b has the value -1 or in hexadecimal like 0xffffffff (provided that sizeof( int ) is equal to 4) due to the propagating the sign bit according to the integer promotions.

Then this byte is overwritten

*cp = 10;

So now the variable a internally has this value 0x10a (10 in hexadecimal is equal to 0x0a) And in decimal the value is equal to 266.

As a result in this call of printf

printf("%d %d %d", a,b,*cp);

there are outputted a that is equal to 266, b that is equal to -1 and the byte of the variable a pointed to by the pointer cp that is equal to 10.