The output value differs from the value received as argument within the function when performing a direct operation


I tried to make 11..10..0 (which is binary number with consecutive 32-n zeros in small digits).

// Can assume that 0 <= n <= 31

int masking(int n) {
  return (~0)<<(~n+33);

However, when I put 0 in input n, I expected 0, but I got -1(0xffffffff).

Without using input,

  • (~0)<<(~0+33) gives 0.

  • (-1)<<32 also gives 0.

I don't know why I got different results.

asked on Stack Overflow Sep 29, 2019 by Guseul Heo • edited Sep 29, 2019 by Kalana

1 Answer


You might want to consider forcing 64 bit math. According to "C" standard, result of shifting of a variable with N bits is only defined when the number of shifts is less than the size of the variable (0..N-1)

Performing the shift on (~0) (integer, usually 32 bit), will result in undefined behavior for ~n+33 (n=0) since ~n+33 = 32, above the limit of 31.

Changing the code to use (~0L) produce the requested result masking(0) = 0

Assuming that you run on generic Linux - gcc will default to 32 bit integer, 64 bit long and 64 bit pointer.

include <stdio.h>

int masking(int n) {
  return (~0UL)<<(~n+33);

void main(void)
        for (int i=0 ; i<4 ; i++) {
                printf("M(%d)=%x\n", i, masking(i)) ;


answered on Stack Overflow Sep 29, 2019 by dash-o • edited Sep 30, 2019 by dash-o

User contributions licensed under CC BY-SA 3.0