2

Is it possible for an integer variable to achieve the value -1 using the following C code -

main()
{
    int n=0;
    while(n++ != -1){
        printf("\n%d",n);
    }
}
PalashV
  • 759
  • 3
  • 8
  • 25
  • 4
    Yes it is, because of the undefined behavior this code has. – The Paramagnetic Croissant Jun 16 '14 at 11:01
  • @AdrianoRepetti, sure it is undefined. Whether or not this UB doesn't depend on the representation. In particular, any compiler can just simply remove that test. – Jens Gustedt Jun 16 '14 at 11:03
  • paver, what exactly do you mean by *"an integer variable to achieve the value -1"*? Are you asking if `-1` will ever be printed, or whether if `n` will ever be `-1`, or something else? – Utkan Gezer Jun 16 '14 at 11:05
  • @JensGustedt yes, I thought about compiler after I posted the comment! – Adriano Repetti Jun 16 '14 at 11:06
  • @Jens: since `int` is signed, I don't believe that there exists any compiler which would actually decide to remove that test. – vgru Jun 16 '14 at 11:08
  • @ThoAppelsin If n will ever be -1. – PalashV Jun 16 '14 at 11:09
  • 1
    @Groo, gcc does such things. I just tested it, it places a simple unconditional `jmp` instruction. – Jens Gustedt Jun 16 '14 at 11:09
  • @Someone: Why people are downvoting such a question. Whoever is that, if he/she is that genius doesn't need to follow this question, as simple as that! – PalashV Jun 16 '14 at 11:11
  • @Jens: is there a reference somewhere which would describe this kind of optimization? It seems highly unlikely to me that the compiler would resort to such kind of static analysis (`n` cannot ever reach `-1` because it was `0` and it's only being increased?), but it would be nice to learn something new. – vgru Jun 16 '14 at 11:20
  • @Jens: never mind, I've found mentions of the behavior (e.g. here: ["The compiler optimized away my overflow checks! What is going on?"](https://gcc.gnu.org/wiki/FAQ#signed_overflow)) – vgru Jun 16 '14 at 11:33
  • Well, using 'short int' (2 bytes on my system) instead of 'int' (4 bytes) helped, and gcc compiler used min value after max value, and at last the program stopped. :) – PalashV Jun 16 '14 at 11:35

3 Answers3

8

Yes, it is. At a certain point, the variable will overflow and may become negative. But note that signed overflow is undefined behavior, so there is no way to know what will happen, and this is the reason why such code should be avoided.

haccks
  • 104,019
  • 25
  • 176
  • 264
alain
  • 11,939
  • 2
  • 31
  • 51
  • Only would be correct, if you'd add a "may" in front of "become negative". In fact, because of the UB after overflow, the compiler might as well optimize out the whole test. – Jens Gustedt Jun 16 '14 at 11:06
  • @JensGustedt thanks for your comment, I added it to the answer. – alain Jun 16 '14 at 11:09
  • 1
    Practically, this is true in most of the cases. E.g. if you're using gcc, you can specify `-fwrapv` when compiling to ensure that overflow results in two's-complement wrapping (although this option might make your code [slower](https://gcc.gnu.org/wiki/FAQ)). – vgru Jun 16 '14 at 11:31
5

There is a theoretical and a practical part to this:

Theoretically, adding one to the max value of an integer will result in undefined behaviour. That may be anything. Pink elephants could be raining from the sky.

In practice, pink elephants were too difficult to implement even for compiler vendors and most of them will simply produce the minimum of the value range if you add one to the maximum of the value range. That means max+1 will result in min.

That way, once you counted from 0 to max, add one to reach min and count up to -1 again, yes, after some time in practice your integer will become -1.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • 1
    No, this is not what is likely to happen. UB here means that the compiler has the right to optimize the test out completely. And compilers do that, so one should be careful. – Jens Gustedt Jun 16 '14 at 11:08
  • @nvoigt - What is 'Pink elephants'? – PalashV Jun 16 '14 at 11:20
  • @paver It's simply a metaphor for "anything can happen". Undefined behaviour is bad. Because even if it seems to work on one day with one compiler, it may not work on another day or another compiler. – nvoigt Jun 16 '14 at 11:24
  • 1
    @paver These: http://www.freemanformula.com/wp-content/uploads/2013/02/pink-elephant-733153.jpg If you ever come across one, try to capture it and sell it to a C compiler vendor. There are hundreds of cases where they are needed, for every case of undefined behavior in the C standard. – Lundin Jun 16 '14 at 13:17
  • @Lundin : Thanks, I'll keep track of them. By the way, as such behavior is compiler dependent, why are they needed then? – PalashV Jun 17 '14 at 06:31
  • @paver It is not compiler-dependent, the compiler might do _anything_, including completely ignoring the code you just wrote, or implement it in a perfectly predictable and safe way, or cause your computer to crash & burn, or send forth a pink elephant. The latter is merely the most popular implementation, which are why such elephants are becoming nearly extinct. – Lundin Jun 17 '14 at 06:39
  • @Lundin : Okay. However, I'm still confused. As nvoigt said, "It's simply a metaphor for "anything can happen"" for 'Pink Elephant', does it only refer to the undefined behavior of a code & it's interpretation? And, is it possible for a code to behave differently after compiling it, at different times (sounds irrational to me but still...) ? – PalashV Jun 17 '14 at 06:49
  • 1
    @paver Well, it turns out we're just teasing you with pink elephant metaphores since everyone is tired of explaining UB yet again. See the [Stack Overflow C FAQ](http://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) for an explanation involving less elephants. It is indeed possible for the code with undefined behavior to behave differently each time. Instead of the unexpected pink elephant, you might as well get the Spanish inquisition. – Lundin Jun 17 '14 at 06:56
2

By default, int variables are signed in C. So, in this case the signed integer overflow invoke undefined behavior. n may or may not become -1.
But if you want to achieve this then declare n as unsigned int. Due to integer overflow you will get -1.

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
  • 1
    @TimCooper; AFAIK, `int` are implicitly `signed`. – haccks Jun 16 '14 at 11:02
  • 2
    I have voted down, because answer doesn't make much sense... The answer is simply **yes**, and this answer was originally saying **no**, and it still has remnants from that on its last paragraph. – Utkan Gezer Jun 16 '14 at 11:09
  • Not my downvote, but both `singed` and `unsigned` integers can overflow. – vgru Jun 16 '14 at 11:10
  • @ThoAppelsin; How this answer doesn't make sense? And I say that answer is simply **NO**. Now you prove how it is **YES** (for certain). – haccks Jun 16 '14 at 11:10
  • @Groo; But `signed` overflow invokes UB. – haccks Jun 16 '14 at 11:11
  • @haccks *"But if you want to achieve this, then declare `n` as `unsigned int`."* What is the thing trying to get achieved here, and how does declaring `n` as `unsigned int` provide any help on that? My guess would be that the aim is to have a non-infinite loop, in which case making such a change would break something not that so broken, i.e. cause an infinite loop. – Utkan Gezer Jun 16 '14 at 11:14
  • @ThoAppelsin; If you declare `n` as `unsigned` the `n` will go to `-1` for sure. But in OP's case there is no guarantee and that's why I suggested that. And now I think these downvotes are intentional. – haccks Jun 16 '14 at 11:15
  • 1
    +1 yes, for sure getting -1 need to be type `unsigned int` but for `int` it will be UB. So for OP's case it may or not. – Jayesh Bhoi Jun 16 '14 at 11:20
  • 1
    Maybe it would be clearer to indicate that `-1` would (in the `unsigned` case) be cast to `unsigned int` and become an unsigned value which would be reached by `n`. – vgru Jun 16 '14 at 11:26