Function Clarification

Hello all.

I have been trying to wrap my head around functions.

If I make a function using Void, will I be able to change the value of variables or arrays within the function and have that value return to the main loop? If not how can I do this? Thanks.

(deleted)

Thanks for the reply.

What do you mean when you say you must declare its return scope? So I would have to change the value within the void and then say return(int, var); if I wanted to change the global variable var to use in the main loop?

You have to change the function definition from:
void foo(){}

to int foo() {return 1;} //And make sure to include a return statement.

Now, you can't change setup() or loop() because the compiler already knows they do not return values.

Could I return multiple values? Or would I have to return an array or something?

If you pass values by reference rather than value you can change their actual value rather than the value of a copy. Hence you don't need to return the value(s) to the calling program.

See what you make of

void setup()
{
  Serial.begin(115200);
  int val1 = 0;
  int val2 = 0;
  aFunction(val1, val2);
  Serial.println(val1);
  Serial.println(val2);
}

void loop(){}

void aFunction(int &valx, int &valy)  //values passed by reference
{
  valx = valx + 123;
  valy = valy + 456;
}

The usual method in an Arduino program is make everything global, if it needs to be changed or accessed by more than one function. That's not a good technique for larger programs, or teams where multiple programmers are working on the same program.

My general principle is to make everything local, except controlling constants that are all #define'd up at the top. Then if something needs to be in more than one function and it doesn't make sense to pass it as a parameter, it gets promoted to global.

Every function has a "signature". for example, suppose you write a function:

int SquareIt(int value)
{
   return value * value;   // Assume no overflow...
}

A function's signature has three parts:

  1. type-specifier
  2. name
  3. parameter list

Our function's signature is:

type specifier Name Paramter list

int SquareIt (int value)

The type specifier tells you the data type that is returned from the function, a int in this case. The function type specifier can be void, which means no value is returned from the function. The function name is whatever you choose to name it, as long as it doesn't conflict with other function names. The parameter list are the variables that are passed to the function so it can perform its task. The parameter list can be empty with no parameters passed to the function.

Calling our function, we might use:

// a bunch of code...
   int answer;

   answer = SquareIt(10);

Because the signature of SquareIt() has a function type specifier of int and it called with the function parameter of 10, answer will equal 100 after the function call.