4

I have posted questions about "my void loop" or "my void setup" and people complain that they aren't really voids. But they are! See this example code:

void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);              // wait for a second
}

Clearly setup and loop are voids because they have the word void right before them!


Note: this is a reference question.

Majenko
  • 105,851
  • 5
  • 82
  • 139
Nick Gammon
  • 38,901
  • 13
  • 69
  • 125

2 Answers2

7

This is an easy mistake for a beginner to C++ to make. Let's look at other languages, like PHP:

function add ($a, $b)
  {
  return $a + $b;
  }

Or Lua:

function add (a, b)
  return a + b
end

Or JavaScript:

function add (a, b)
  {
  return a + b;
  }

Or VBscript:

Function add (a, b)
  add = a + b
End Function

All those languages have the word "function" there to indicate that you are declaring a function.


So what does C++ look like:

int add (int a, int b)
  {
  return a + b;
  }

So this must be an "int" right? Or what if it doesn't return a value?

void loop ()
  {
  }

Now it's a "void"? Kind of a weird name for a function!

Actually int and void in these examples are not weird names for functions. They are the return types of those functions. int add (int a, int b) is a function that returns an int. And void loop () is a function that returns nothing.

The C++ compiler can deduce when it is seeing a function declaration from some clues:

  • A return type (eg. int, float, long)
  • A name (the function name)
  • Some parentheses (for the function arguments)

Think of the word function as being there in spirit:

int [function] add (int a, int b)
    ^^^^^^^^^^   <-- don't actually type this!
    {
    return a + b;
    }
Edgar Bonet
  • 45,094
  • 4
  • 42
  • 81
Nick Gammon
  • 38,901
  • 13
  • 69
  • 125
0

I think if you use a phrase like " my int a or my CustomType a " people would interpret those phrases to mean that you have a variable a that is an instance of an int or a CustomType.

According to http://en.cppreference.com/w/cpp/language/types you can't have an object or reference of type void.

If you have a phrase like "my void setup", I think most people would try to read that as implying you have a variable setup of type void, which I don't think makes sense, to most people.

What you actually have is this:

void setup() {
...
}

I think most people would phrase this as "my function setup, which takes no arguments are returns nothing".

nPn
  • 174
  • 4