Member Avatar for fougere

In the following example:

int a = 2;
float b = 3.2;
float c = a+b;

Is 'c' 5 or 5.2? Is there a rule, like "lower precision types are promoted" for example, or is there a rule like "the first operand is converted to the same type as the second"?

Thanks.

yes there is a rule. types are promoted to a higher type if assigned to a higher type. going from a higher type to a lower type works as well but there can be truncation of the number

int foo = 5;
float bar = 3.5;
float result = foo + bar;
// result is now 8.5 because foo gets converted to a float and then added.

float foo = 3.5;
float bar = 2.14;
int result = foo + bar;
// result is now 5 because foo + bar is 5.64 and converting that to an int you get 5

yes there is a rule. types are promoted to a higher type if assigned to a higher type. going from a higher type to a lower type works as well but there can be truncation of the number

That's not the complete picture, types are promoted to a higher type if used in a calculation with a higher type or when assigned to a higher type, whichever happens last so

int foo = 5;
float bar = 3.5;
float result = foo + bar;
// result is now 8.5 because foo gets converted to a float and then added.

// but
int foo = 5;
int bar = 2;
float result = foo / bar;
// result is 2.0 not 2.5 because the calculation uses integer arithmetic

In the second example the values are not promoted to float until after the calculation has happened and the result is stored in result. That means that the calculation takes place using ints and integer arithmetic and all fractions are dropped.

Sorry forgot about that part. Thanks for adding that Banfa.

Member Avatar for fougere

great. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.