tags:

views:

188

answers:

6

Testing a couple of compilers (Comeau, g++) confirms that the result of a bitwise operator of some "integer type" is an int:

void foo( unsigned char );
void foo( unsigned short );

unsigned char a, b;

foo (a | b);

I would have expected the type of "a | b" to be an unsigned char, as both operands are unsigned char, but the compilers say that the result is an int, and the call to foo() is ambiguous. Why is the language designed so that the result is an int, or is this implementation dependent?

Thanks,

+8  A: 

This is in fact standard C++ behavior (ISO/IEC 14882):

5.13/1 Bitwise inclusive OR operator

The usual arithmetic conversions are performed; the result is the bitwise inclusive OR function of its operands. The operator applies only to integral or enumeration operands.

5/9 Usual arithmetic conversions

Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:

  • If either operand is of type long double, the other shall be converted to long double.
  • Otherwise, if either operand is double, the other shall be converted to double.
  • Otherwise, if either operand is float, the other shall be converted to float.
  • Otherwise, the integral promotions shall be performed on both operands.
  • ...

4.5/1 Integral Promotions

An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of type unsigned int.

I think it has to do with int supposedly being the "natural" size for the execution environment to allow for efficient arithmetic (see Charles Bailey's answer).

In silico
Looks to me like it says **can be**. IOW: If your compiler may or may not promote to int.
T.E.D.
@T.E.D.: It say "can be", because the target type *can be* either `int` or `unsigned int`. That the only "can be" that exists here. As for the promotion itself, it is always unconditionally required.
AndreyT
@AndreyT - That isn't true. "... can be converted ... if int can represent all the values of the source type; otherwise ... can be converted to ... unsigned int". Since it says "can be" in the second option, the entire conversion is optional.
Merlyn Morgan-Graham
@T.E.D, Merlyn: no, AndreyT is right. The "can be" here defines what integral promotions are possible. The rules on usual arithmetic conversions state that the integral promotions "shall be" applied. The compiler has the freedom to decide which promotion can be done (by choosing the widths of the types), but having made that choice it "shall" perform the promotion. Anyway "can be" in the C++ standard generally means it's something possible, something the programmer can cause to happen, not an optional feature.
Steve Jessop
@Merlyn Morgan-Graham: No, all "can be"s in this text come from the dependence of this part of specification on such implementation details as ranges of "smaller" types. But the promotion itself is unavoidable. C/C++ *never* perform arithmetic on types smaller than `int`/`unsigned int`.
AndreyT
@T.E.D, Steve Jessop, AndreyT: Oops, missed the "Otherwise, the integral promotions shall be performed". To ape Jeff Foxworthy, "Your language might have a complexity problem if..."
Merlyn Morgan-Graham
A: 

It seems this is the same thing as in Java:

Short and char (and other integers smaller than an int) are weaker types than int. Every operation on these weaker types is therefore automatically unboxed into an int.

If you really want to get a short, you will have to typecast it.

Unfortunately I can't tell you why this was done, but it seems this is a relatively common language decision...

Sarek
`short` to `int` conversion is not 'unboxing'. Unboxing is such things as `Integer` to `int` (the reverse being 'boxing'). `short` to `int` is simply an implicit cast (as opposed to an explicit cast: `int a = 123; short b = (short)a;`).
Brian S
A: 

Isn't short the same as short int? in the same way that long is synonymous with int. eg. a short is an int taking up less memory then a standard int?

Adam Naylor
`long` is not synonymous with `int`. The relationship between the types is that the size of `char <= short <= int <= long`, with additional rules stipulating the minimum size of each of the types.
James McNellis
+1  A: 

int is supposed to be the natural word size for any given machine architecture and many machines have instructions that only (or at least optimally) perform arithmetic operations on machine words.

If the language were defined without integer promotion, many multistep calculations which could otherwise naturally be mapped directly into machine instructions might have to be interspersed with masking operations performed on the intermediates in order to generate 'correct' results.

Charles Bailey
Personally I still question this. Either the intermediate masking changes the final result, or it doesn't. When it doesn't, the compiler could skip it. When it does, the 'no arithmetic smaller than int' rule introduces "surprising behaviour" - fast results which are "wrong" w.r.t the types of the operands. An alternative would be just not to define any operators that would be "too slow" in their reasonably "expected" meanings. Of course C hackers back in the day didn't have quite the same expectations of usability we do now ;-)
Steve Jessop
... a more convincing argument to me is that if you're doing arithmetic on shorts, you're bound to need to check for overflow sooner or later, so the compiler might as well save you from yourself.
Steve Jessop
@Steve: In other words, all the calculations could be done in `int` by the as-if rule?
David Thornley
@David: well, if the only opcodes available are for ints, then the calculations would be done using ints and then massaged into shape. That's not precisely the result of the 'promote to at least int' rule, though. If `a` and `b` are `unsigned short` of width 16 bits, the question at stake is whether `(a + b) -)
Steve Jessop
@Steve - I'm sure we've all overflowed 32 bits and even 64 bits before. After all, all it takes is a factorial, and we've all done that if only as a kind of hello world. So - doesn't your logic argue that all integers should be promoted to arbitrary precision integers to save us from ourselves? And after that - well, maybe the truncating division behaviour is surprising. Maybe we should promote everything to an arbitrary precision rational library? But then, what if someone takes the square root of 2, then squares the result... maybe we need symbolics to save us from ourselves?
Steve314
@Steve314: It's true that `int` and `long` sometimes overflow, but my practical experience is that `short` will *almost always* overflow if you're doing much arithmetic beyond increment, because I rarely have real problems where the numbers stay that small. Those who've programmed extensively on 16bit micros might disagree: they may have been using smaller numbers for smaller problems ;-). As for truncation being "surprising" - I mean surprising from the POV of someone scanning the code, not surprising from the POV of someone with no conception that computers might have limited abilities.
Steve Jessop
... In fact my logic does suggest that all those things you mention would be useful, but they have heavy performance and memory cost on the kind of machines where C was designed. The 'promote to at least int' rule, while it does occasionally throw up surprises, does have basically no performance cost except in odd cases like the one I invented, because by definition `int` should be given a size which is "fast" on the architecture. With occasional exceptions, but only for architectures which really are unsuited to C in the first place, (similarly: 16bit POSIX).
Steve Jessop
@Steve - the thing is, if someone has specifically chosen to use an integer type smaller than an int, assuming they need "saving from themselves" isn't consistent with the overall style of C and C++. There may be good reasons for doing arithmetic with smaller integers. One of those reasons is that someone may *want* the overflow behaviour. Wanting modulo 2^n arithmetic isn't that rare. If someone scanning the code cannot notice that small integer types have been specified, that someone shouldn't be reading the code - he won't understand it irrespective of arithmetic behaviour.
Steve314
@Steve - also, if you believe its impossible for apparently intelligent programmers to object to division causing trunction, take a look at http://www.python.org/dev/peps/pep-0238/ - those guys objected to truncation by default so much, they changed the semantics of the standard division operator. The points about rationals and irrationals were exaggerated, but... well, if people will change standard operators over truncation, how long before someone points out that using floats by default is premature optimisation - in a few years Python'll probably change to using rationals instead.
Steve314
@Steve314: I never said what you say I believe. I said that my argument suggests promotion to rational would be useful, but not (at the time) affordable. As for modulo arithmetic - yes, very rarely someone wants it, but IMO the only excuse for it being default behaviour is because it's cheap. Usually a hardware exception would actually be preferable. In a hypothetical world where we don't have to worry about implementation costs, modulo arithmetic would be a really stupid default. It should be tucked away in a corner, and preferably support arbitrary modulus.
Steve Jessop
@Steve - that's interesting because what I believe you said is "As for truncation being "surprising" - I mean surprising from the POV of someone scanning the code, not surprising from the POV of someone with no conception that computers might have limited abilities.". I think you misunderstand me though. I don't believe the integer arithmetic behaviour is wrong. I believe your "the compiler might as well save you from yourself" claim is wrong - neither C nor C++ make a habit of second-guessing whether the programmer really intended to do what he did.
Steve314
A: 

Neither C nor C++ ever perform any arithmetic operations on types smaller than int. Any time you specify a smaller operand (any flavor of char or short), the operand gets promoted to either int or unsigned int, depending on the range.

AndreyT
A: 

I would have expected the type of "a | b" to be an unsigned char, as both operands are unsigned char,

My reading of some beginner C books in past left the impression that bitwise operators were left in the language solely for the purpose of the system programming and generally should be avoided.

The operators are performed by the CPU itself. CPU uses for operands registers (which are surely larger than char) and thus compiler cannot know how much bits of a register would be affected by the operation. To not to loose the full result of the operation, compiler upcasts the result to the proper operation. AFAICT.

Why is the language designed so that the result is an int, or is this implementation dependent?

Bit-level representation of data types is in fact implementation defined. That might be the reason why apparently bit-wise operations are also implementation defined.

Though C99 defines in 6.2.6.2 Integer types how they should appear and behave (and later how bitwise operations should work) the particular chapter gives a lot of freedom to the implementation.

Dummy00001