+ 1

Why the result is 0 in this code???

The result of the attached code is 0. If you remove the 'unsigned' keyword from the pointer "p", the printed result changes to 1. It's not matters if is a comparison between diferent types, primarily. The 'unsigned' keyword seems to rule/determine the final output. What the reasons for such behavior? https://code.sololearn.com/c30mn0X1BjxC/?ref=app

23rd Jan 2019, 7:23 PM
Daniel Bandeira
Daniel Bandeira - avatar
13 RĂ©ponses
+ 3
https://code.sololearn.com/cZgn97tb2b11/?ref=app
23rd Jan 2019, 11:15 PM
Zen
Zen - avatar
+ 2
Oh, got it, that's because the negative signed value 0xff is sign extended with extra 1's when converted to an int for the comparison, while the positive unsigned 0xff is just padded with 0's. signed char 0xff is -1, and -1 as an int is 0xffffffff unsigned char 0xff is 255, which translates to 0x000000ff as an int The value of j is a red herring, you can set it to 0x123456FF and it won't change anything.
23rd Jan 2019, 10:51 PM
Zen
Zen - avatar
+ 1
Overflow? 0xFFFFFFFF is -1, so an unsigned char can't be equal to j
23rd Jan 2019, 7:30 PM
Anna
Anna - avatar
+ 1
unsigned char 0xff is int 0x000000ff in little endian.
23rd Jan 2019, 11:07 PM
Zen
Zen - avatar
0
The bit pattern is the same,what would really matter to CPU... or Not?
23rd Jan 2019, 8:02 PM
Daniel Bandeira
Daniel Bandeira - avatar
0
Char type has a size of 1 byte, and 0xffffffff has a size of 4 bytes. 0xffffffff is truncated to 0xff as a result when getting *p. Edit: Woops, didn't read the comment. Also, that's not it, see my other post.
23rd Jan 2019, 9:41 PM
Zen
Zen - avatar
0
In this case, why the changing of value depending on the 'unsigned' keyword?
23rd Jan 2019, 10:10 PM
Daniel Bandeira
Daniel Bandeira - avatar
0
Great!!! But I didn't get yet... Could you give a short example using a bit pattern representation (a nibble is sufficient)? If I started to get it,the central reason is the casting performed implicitily by the compiler? And,if this case, must be a earling binding? (a side question?)
23rd Jan 2019, 11:00 PM
Daniel Bandeira
Daniel Bandeira - avatar
0
resuming... when comparing 0xFF (char) becomes 0xFF000000 (int) ?
23rd Jan 2019, 11:03 PM
Daniel Bandeira
Daniel Bandeira - avatar
0
Right... and the unsigned keyword... what does it do after all?
23rd Jan 2019, 11:11 PM
Daniel Bandeira
Daniel Bandeira - avatar
0
what happens when I put char without unsigned?
23rd Jan 2019, 11:12 PM
Daniel Bandeira
Daniel Bandeira - avatar
0
Thank you too much!!!
23rd Jan 2019, 11:16 PM
Daniel Bandeira
Daniel Bandeira - avatar
- 1
I got now!!! unsigned => 0xFF expands to 0x000000FF signed char => 0xFf expands to 0x800000FF ???
23rd Jan 2019, 11:14 PM
Daniel Bandeira
Daniel Bandeira - avatar