Has everyone forgotten Pascal?
0.1666666... (to whatever precision is supported).
1 div 6 yields
It's arguable whether the C rule is a mistake. Almost all of C's arithmetic operators, where the operands are of the same type, yield a result of the same type. There's something to be said for consistency.
Furthermore, since C is primarily targeted at system-level code, most C programs don't use floating-point at all. At one time, accidentally adding floating-point code to a program that didn't otherwise need it could be a serious problem. That's probably still the case, for small embedded systems -- which, again, are a major target for C.
In most C programs, truncating integer division is probably just what you want anyway.
1 / 6 yielded a floating-point result in C, then:
- It would be an inconsistency in the language.
- The standard would have to make an arbitrary choice of which floating-point type to use for the result (
double may seem like the natural choice, but you might prefer the extra precision of
- The language would still have to have an operation for integer division; performing floating-point addition and then truncating would likely not be good enough.
C could have provided separate operators for the two kinds of division, but the second point above would still apply: which of the three floating-point types would be used for the result? And since it's easy enough to get floating-point division if you need it (use a floating-point constant for one or both of the operands, or cast one or both of the operands to a floating-point type), it apparently wasn't considered that important.
In the 1974 version of the C manual (that's 4 years before the publication of the first edition of K&R), Ritchie doesn't even mention the possible confusion:
The binary / operator indicates division. The same type considerations as for multiplication apply
which says that if both operands are of type
char, the result is of type
Yes, it's a source of confusion for some C programmers, especially beginners -- but C is not noted for being very novice-friendly.