-7

I'm quite new to c++,and I'm wondering whether you can add different number types together,like this:

int num1=1;
float num2=1.0;
double num3=1.0;

can you add these variables together?If you can,what type would

num1+num2+num3

be?

3 Answers3

1

The answer is double. if you want to test it, you can try auto ret = num1+num2+num3 ans see that type ret has.

hopflink
  • 181
  • 12
1

As already said, the answer will be double.

What the compiler will do for this (without optimization) is

  1. Read literal 1 into num1
  2. Read literal 1.0f into num2
  3. Read literal 1.0 info num3
  4. Convert integer num1 to float num1'
  5. Add num1' and num2, result is float tmp
  6. Convert float tmp to double tmp'
  7. Add tmp' and num3 to get the final double result

You need to take some care with these conversions. Whilst you can convert float (and int) to double without any loss of precision, you can't always do the same with int to float.

float has 24 bits of precision, which means that it can exactly represent all integers up to about 16.8 million, while a signed int can go up to about 2 billion. See here for details.

[I'm assuming the LP64 model]

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
  • Beware, `int` is not always convertible to `double` without loss of precision. This is the case on architectures where `sizeof(int) == sizeof(double)` for instance. – YSC Oct 03 '18 at 09:40
  • I doubt that the OP is using anything like an old Cray machine. – Paul Floyd Oct 03 '18 at 09:46
  • You're mistaken, some new arch's have that trait where an int is the same size as a pointer. – YSC Oct 03 '18 at 09:53
  • What does the pointer size have to do with anything? Currently anything but LP64, LLP64 and ILP32 is very exotic. Maybe some new RISC-V systems will be IPL64? – Paul Floyd Oct 03 '18 at 10:05
  • On my home computer, intel i7 + Linux x64, `sizeof(int) == sizeof(void*) == sizeof(double)`. – YSC Oct 03 '18 at 10:07
  • And what distro / compiler / options would that be? – Paul Floyd Oct 03 '18 at 12:16
-6

Yes of course... the result will give a float 1+1.0+1.0=3.0 since double