Hi Everyone,
Below is the snippet of code that I was trying to execute
Code:
typedef char s8;
typedef unsigned char u8;
int main(void)
{
//range for char is -128 to +127
//range for unsigned char is 0 to 255
// range for int is -2,147,483,648 to 2,147,483,647
// range for unsigned int is 0 to 4,294,967,295
s8 *ptr, var1=110;
u8 *ptr2, var2 = 250;
ptr = &var2;
ptr2 = &var1;
printf("Values when datatypes are interchanged are %d and %d\n", *ptr, *ptr2);
return 0;
}
The idea was to check how this code works at background when playing with different datatypes with pointer and here is the output of the program which was expected.
Code:
Values when datatypes are interchanged are -6 and 110
Here is the assembly code compiled in GCC 9.3
Adding code for just 2 lines of code as my query is limited to it:
Code:
push rbp
mov rbp, rsp
mov BYTE PTR [rbp-1], 110
mov BYTE PTR [rbp-2], -6
mov eax, 0
pop rbp
ret
As seen from above , the value is initialized with -6 and not 250. My consideration was that value should initialized with 250 value since its unsigned char datatype and its range is between 0 to 255.
Again, I tried something new and added one more variable of datatype unsigned int with value 2147483647 (0x7FFFFFFF) and its assembler is as below:
Code:
push rbp
mov rbp, rsp
mov BYTE PTR [rbp-1], 110
mov BYTE PTR [rbp-2], -6
mov DWORD PTR [rbp-8], 2147483647
mov eax, 0
pop rbp
ret
and when I added 1 into it:
Code:
char *ptr, var1=110;
unsigned char *ptr2;
unsigned char var2= 250;
unsigned int var3 = 2147483647+1;
its assembler code changes to
Code:
push rbp
mov rbp, rsp
mov BYTE PTR [rbp-1], 110
mov BYTE PTR [rbp-2], -6
mov DWORD PTR [rbp-8], -2147483648
mov eax, 0
pop rbp
ret
in which it is initialized with -2147483648 and not with 2147483648.
Can anybody explain that why the signed range follows even the variables are unsigned?
Thanks in advance