Subj : Re: overflow in C To : comp.programming From : Peter Ammon Date : Wed Sep 21 2005 12:10 pm DarkD wrote: Please don't top post. > For unsigned a modulo is performed with the max number of values, so a char > set to 257 will be 1. > >>signed char a = 130; >> >>I explicitly generate an overflow since the maximum value a singned char >>can accommodate is "127". Is this behavior of the overflow defined in any >>way or do I get an undefined state of "a" due to the C standards? > > > > > C99 says its 'undefined behavoiur' if its signed. Short answer: No it's not. It's implementation defined. Long boring answer: From 6.7.8 #11: The initializer for a scalar shall be a single expression, optionally enclosed in braces. The initial value of the object is that of the expression (after conversion); the same type constraints and conversions as for simple assignment apply, taking the type of the scalar to be the unqualified version of its declared type. Thus, signed char a = 130; is the same as signed char a; a = 130; and uses the same conversion scheme. And what's that? From 6.3.1.3: [#1] When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged. [#2] Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type. [#3] Otherwise, the new type is signed and the value cannot be represented in it; the result is implementation-defined. To be clear: signed type conversions like char a = 130;, someChar = someBigInt, or (char)someBigInt; are all implementation defined. unsigned conversions work the way you'd hope. (OTOH, overflows, like int a = INT_MAX; a += 1; are undefined behavior.) > This is because a > computer could be using one's compliment or two's compliement, or even > ignores the most significant bit. A compiler is allowed to error on > this (and should), A compiler is free to emit warnings on this (and should), but it must also compile it. Implementation defined behavior does not give the compiler enough latitude to abort compilation (see 4 #3). > alot ignore it. Bad compiler! Bad! Bad! -Peter -- Pull out a splinter to reply. .