What are the implicit types for numbers in C? If, for example, I have a decimal number in a calculation, is the decimal always treated as a double? If I have a non-decimal number, is it always treated as an int? What if my non-decimal number is larger than an int value?
I’m curious because this affects type conversion and promotion. For instance, if I have the following calculation:
float a = 1.0 / 25;
Is 1.0 treated as a double and 25 treated as an int? Is 25 then promoted to a double, the calculation performed at double precision and then the result converted to a float?
What about:
double b = 1 + 2147483649; // note that the number is larger than an int value
If the number has neither a decimal point nor an exponent, it is an integer of some sort; by default, an
int.If the number has a decimal point or an exponent, it is a floating point number of some sort; by default, a
double.That’s about it. You can append suffixes to numbers (such as
ULLforunsigned long long) to specify the type more precisely. Otherwise (simplifying a little), integers are the smallestinttype (of typeintor longer) that will hold the value.In your examples, the code is:
The value of
ais calculated by noting that1.0is a double and25is an integer. When processing the division, theintis converted to adouble, the calculation is performed (producing adouble), and the result is then coerced into afloatfor assignment toa. All of this can be done by the compiler, so the result will be pre-computed.Similarly, on a system with 32-bit
int, the value214783649is too big to be anint, so it will be treated as a signed type bigger thanint(eitherlongorlong long); the1is added (yielding the same type), and then that value is converted to adouble. Again, it is all done at compile time.These computations are governed by the same rules as other computations in C.
The type rules for integer constants are detailed in §6.4.4.1 Integer constants of ISO/IEC 9899:1999. There’s a table which details the types depending on the suffix (if any) and the type of constant (decimal vs octal or hexadecimal). For decimal constants, the value is always a signed integer; for octal or hexadecimal constants, the type can be signed or unsigned as required, and as soon as the value fits. Thanks to Daniel Fischer for pointing out my mistake.