Search code examples
c++functionintparentheses

Can anybody explain me like i'm 5 how the variables work on a function?


So for the past 4 months i've been learning C++ and I made lots of progress, actually getting very close to learning graphs soon. There's just one thing that I still have problems and and I just don't get it, and that is the variables on a function.

Basically I do not know what kind of variables to put inside the () of a function in the beginning, and what variables I need to put after.

I know it depends on the exercise, so i'll try to give an example.

so I want to calculate the sum of a and b in a function.

int calculateSum(int a, int b){
    int sum;
}

so why do I put under the function and not inside the parenthesis? why can't it just be like:

int calculateSum(int a, int b, int sum){
    //code
}

Solution

  • Variables inside the () are the parameters of your function. That is, the inputs it expects when it is called from other code. The variables inside the {} are for use exclusively inside your function.

    Your first example makes sense - you'd use it something like this:

    int answer = calculateSum(1, 2);
    

    What would you pass as an argument for the sum parameter in your second example? It's sort of a meaningless request - the caller of your function wants to get the sum back from your routine.