1

I have a problem with how ~ works in C in the code snippet below:

#include <stdio.h>
int main()
{
unsigned char x[256];
int i = 0;
for(i=0; i<256; i++)
    x[i] = i;

unsigned char index = 1;
unsigned char y = 0;

//Case 1
y = x[~index];
printf("%u\n", y);
//Output: 0

//Case 2
y = x[(unsigned char) ~index];
printf("%u\n", y);
//Output: 254    

//Case 3
y = x[index ^ 0xFF];
printf("%u\n", y);
//Output: 254

return 0;
}

The case 1 does not return the correct result while case 2 and case 3 do. It seems to me that ~index gets interpreted as an int and not a char. This would be OK however I do not understand why unsigned char get one extended during the bit-wise not.

Compiled using: gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1)

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Swietowid
  • 19
  • 1
  • 3
    `~1 == -2` (assuming a two's-complement machine). You are accessing some random memory that happens to sit at an address right before `x`. The program exhibits undefined behavior, so any outcome at all is in fact the correct one. – Igor Tandetnik Apr 10 '15 at 14:14
  • 2
    See [C++ - Bit-wise not of uchar produces int](http://stackoverflow.com/q/26101257/1708801) – Shafik Yaghmour Apr 10 '15 at 14:14

0 Answers0