1

What am I doing wrong here in C, because if I run the following code I get only 0.000000 instead of 20.5?

int testInt= 10;
double testDouble = 10.5;
auto testSum = testInt + testDouble;

printf("%lf\n",&testSum);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
  • 4
    `printf("%lf\n", &testSum);` -> `printf("%lf\n", testSum);`, your compiler probably warned you. If not, compile with `-Wall`. Also `auto` is not a valid keyword in C, only in C++. – Jabberwocky Mar 30 '22 at 13:45
  • 3
    `auto` is not a type but storage class. Your `testSum` has a default `int` type. – Eugene Sh. Mar 30 '22 at 13:48
  • Ok, than i'll not use auto, but also if i set the variable on double it doesn't work. And yes, i have also removed the & at the printf command. What do you mean with compile with -Wall? – Codemaster2022 Mar 30 '22 at 13:51
  • 1
    @Codemaster2022 so does it work as expected if you remove the `&` in front of `testSum`? – Jabberwocky Mar 30 '22 at 13:52
  • As @EugeneSh. said the type for `testSum` is `int` by default. So you must use the `%d` type in `printf`. I.e. `printf("%d\n", testSum);`. If you want use doubles then define it as: `double testSum`, then `printf("%lf\n", testSum);` can be used. – Frankie_C Mar 30 '22 at 13:53
  • No, it just doesn't work. Whyever – Codemaster2022 Mar 30 '22 at 13:53
  • Why is it that when I write the code with the modifications that you said you have done, it works for me? – Cheatah Mar 30 '22 at 13:54
  • Yes, but then i get 20 as resoult instead of 20.5 . And i'd like to mixed up the different types – Codemaster2022 Mar 30 '22 at 13:55
  • Cheatah, really? No it really dont work for me int testInt = 10; double testDouble = 10.5; int testSum = testInt + testDouble; printf("%lf\n", testSum); – Codemaster2022 Mar 30 '22 at 13:56
  • Oh, i have found the mistake i had to write double test sum not int testsum. Now it works! – Codemaster2022 Mar 30 '22 at 13:57
  • 4
    @Codemaster2022 before I wrote "also `auto` is not a valid keyword in C, only in C++": this is not quite true. `auto testSum = testInt + testDouble;` is actually valid in C, but it does not what you think it does. In C++ `auto` lets the compiler deduce the type automatically depending on the type of the expression on the right side of the `=`. Here that type is `double`. But in C `auto testSum = testInt + testDouble;` is equivalent to `testSum = testInt + testDouble;` which in turn is equivalent to `int testSum = testInt + testDouble;` in this case. – Jabberwocky Mar 30 '22 at 13:59
  • 2
    @Codemaster2022 Read more about the (useless and almost never used auto keyword in C) here: https://stackoverflow.com/questions/2192547/where-is-the-c-auto-keyword-used – Jabberwocky Mar 30 '22 at 13:59
  • @Jabberwocky: `auto testSum = testInt + testDouble;` is not equivalent to `testSum = testInt + testDouble;`. The former is a declaration. The latter is a statement. – Eric Postpischil Mar 30 '22 at 17:55

0 Answers0