That error message is very unhelpful to beginners.
As mentioned, you must always give any function a return type. If you don't want to return anything, you can put "void" as the return type.
But in your code, you are returning something, which is the value of x, after it has been updated, so the return type should be int.
However, there is no need for your function to return anything, because
- it updates x, which is a global variable
- when the function is called, it doesn't do anything with the return value, so the return value is discarded.
Here's one way to fix:
int a;
int x;
void setup() {
Serial.begin(115200);
}
void myfun(){
x=(2*a);
}
void loop() {
a=5;
myfun();
Serial.println(x);
}
Notice I moved the declaration of myfun() to before it is called. The Arduino IDE does not give an error if you do not do this, but most other languages and IDE will give an error, so it's a good habit to get into.
A better version:
int a;
int x;
void setup() {
Serial.begin(115200);
}
int myfun(){
return (2*a);
}
void loop() {
a=5;
x = myfun();
Serial.println(x);
}
This is better because now, x could be a local variable inside loop(). It's better to have fewer global variables because in more complex code, using them can lead to messy, confusing code.
Even better:
int a;
int x;
void setup() {
Serial.begin(115200);
}
int myfun(int z){
return (2*z);
}
void loop() {
a=5;
x = myfun(a);
Serial.println(x);
}
Now, a can also be a local variable inside loop(). It's value is passed as a parameter to myfun() so myfun() can be given any variable or value as it's parameter and isn't fixed to using only a.
You can now also shorten the code:
void setup() {
Serial.begin(115200);
}
int myfun(int z){
return (2*z);
}
void loop() {
Serial.println(myfun(5));
}