-1
void setup()
{ 
  int calc(9,2);
  Serial.begin(9600);
}

void loop()
{}

int calc(int val1, int val2)
{
  Serial.print(val1 + val2);
}

It's not syntax error, i am getting output as 1, i should get 11.

  • 3
    what is int calc(9,2);? you print before Serial.begin() – Juraj Mar 9 at 8:33
  • There are two serious warnings, indicating that the compiler obviously does not understand your intentions. ( Neither do I :) ) – DataFiddler Mar 9 at 22:58
2

A function's name should tell what it does.

Something called calc() should not mainly print (except for debug purposes))

void setup() { 
  Serial.begin(9600);
  printSum(9,2);
}
void loop() {}

void printSum(int val1, int val2) {
  Serial.print(val1 + val2);
}

The other good approach is to really define a function returning a result.

int calc(int a, int b) {
   return a+b;
}
void setup() {
   Serial.begin(9600);
   Serial.println(calc(9,2));
}
void loop() {}
| improve this answer | |
1

If your goal is to call your function with int calc(9,2);, you might want to change it to calc(9,2);, this is the way to call functions, no type declarator needed if you arent creating said function (or in a declaration, wich has nothing to do in the setup) If you want to declare your functions, it must be done at the very top of your code, out of the setup function, and with arduino 1.8.9 on my end, this is not mandatory.

Also, you are calling your printing function before the Serial.begin(), one good practice may be to Serial.begin() at the very top of your setup, so you don't make mistakes on why your debug is not showing.

As on why you have a 1 printed, if that's all your code, i don't really know, i have no output when i try your code on my end

tl;dr;

void setup() {
  Serial.begin(9600);
  calc(9,2);
}
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.