Passing Variables


Passing variables to functions is just as easy! Let's take another look at everyone's favorite example code:

void hello_world(void)
{
    cout << "Hello World!\n";
}

What if you wanted to pass variables to this function, so you could change what it said each time you ran it? You'll be happy to know that it's almost exactly the same as how you did it in Pascal.

As you know, you declare an integer named "foo" by saying "int foo". To create a function that gets passed an integer named "foo", all you do is say the same thing in the parenthesis:

void hello_world(int foo)
{
    cout << "Hello " << foo << "!\n";
}

How do you pass more than one variable, you ask? It's just as easy! All you do is separate the variable declarations with commas. Here's an example:

void hello_world(int foo, float boo, char taco)
{
    cout << "Hello " << foo << ", have you seen ";
    cout << boo << "? I know he's around here somewhere.\n";
    cout << "Also, where's " < taco << "?\n";
}

Note that for every parameter in that, a type was given. Unlike Pascal, C++ requires that you say what kind of variable each parameter is.


Table of Contents

Procedures/Functions | Returning Values | Passing Variables | Using Functions
Function Overloading | Default Parameters | Exercises