Re: infinite for-loop and related question

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 16 February 2011 21:37, Bob Plantz wrote:
> On 02/16/2011 12:41 PM, Jason Mancini wrote:
>>
>> Though I still find the output of this odd:
>>
>>   for (char i(1); i>0; ++i)
>>     printf("%d %d\n", i, sizeof(i));
>>
>> ...
>> 362195 1
>> 362196 1
>> 362197 1
>> ...
>>
>> For very large values of char!  ^_^
>>
>> Jason
>
> That's odd. With g++ 4.4.5 on an x86-64 machine in 64-bit mode I get:
>
> ---
> 125 1
> 126 1
> 127 1
>
> which is what I would expect. That is, i is a (signed) char, and when it
> goes over 127 it becomes a negative number, so the loop terminates.

That would be the expected result if char was unsigned. But as I've
already explained up-thread, when a signed integer overflows you get
undefined behaviour.  If you enable optimisation you might get Jason's
result, or you might have demons fly out of your nose, or your hard
drive might get formatted*


* results may vary, empirically I've only seen it wrap to a negative
number or keep getting larger. But I avoid undefined behaviour because
I'm worried about the nasal demons. You should be too.



[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux