-6

How this program makes the following output? Program

#include<stdio.h>
int main()
{
printf("%x", -1<<1);
getchar();
return 0;
}

Output

fffffffe
proversion
  • 573
  • 3
  • 12
  • 24
  • 3
    Which of the things are you confused about, the result of the calculation `-1<<1` or the result of the `x` formatter. Also, what did you expect? What result would not have made you raise your eyebrows? – Mr Lister Jun 02 '16 at 18:26
  • 1
    Yeah - looks like a reasonable result to me: 0b11111111111111111111111111111110 – Martin James Jun 02 '16 at 19:49
  • If my answer solved your problem, click the big checkbox to accept it as the answer. This will indicate to the community that you found a solution and will give some reputation to you and the answerer. – 2501 Jul 05 '16 at 20:49

1 Answers1

3

Left shift of a negative signed integer value is undefined in C.

6.5.7 Bitwise shift operators

  1. The result of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are filled with zeros. If E1 has an unsigned type, the value of the result is E1 × 2 E2 , reduced modulo one more than the maximum value representable in the result type. If E1 has a signed type and nonnegative value, and E1 × 2 E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

In your case the type of -1 is signed int. The result you're seeing isn't meaningful and is an artifact of the architecture.

Community
  • 1
  • 1
2501
  • 25,460
  • 4
  • 47
  • 87
  • 2
    _undefined behaviour_ actually is a bit worse than just "undefined". It is something to definitively avoid. – too honest for this site Jun 02 '16 at 19:05
  • 2
    correct, an "*artifact of the architecture*" which interprets `-1*2` resulting in `-2` by its bit-pattern as an `unsigned int` when printing (on this specific implementation on this specific architecture). The result might be different somewhere else. – alk Jun 02 '16 at 19:27
  • @Olaf Do you have a good C only link on ub? I feel like there should be one that is highly upvoted but I can't find it. – 2501 Jun 02 '16 at 19:29
  • @alk Yes. Can I include that in the answer? Off-topic: I would love to hear your opinion on this question if you have the time (it isn't urgent): https://stackoverflow.com/questions/37597855/c-order-of-evaluation-of-assignment-statement – 2501 Jun 02 '16 at 19:33
  • Sure, go ahead ... :-) – alk Jun 02 '16 at 19:36
  • "*link on ub*": http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior – alk Jun 02 '16 at 19:48
  • I see @alk already provided a link. However, Wikipedia has an article about it (for various languages) and the standard provides a definition in []3.4.3](http://port70.net/~nsz/c/c11/n1570.html#3.4.3) along with the other kinds of behaviour (miss-behaviour, mister-behaviour, etc.:-). – too honest for this site Jun 02 '16 at 23:53