Difference between passing a parameter or just making a variable?

What’s the difference or should I say, the advantage of passing a parameter in a function, instead of just creating a variable and using that?

1 Like

Because you can make your code more generic by passing variables to functions (in any language you can think of). Suppose I have a function where I want to calculate two numbers, say, 1 + 1. I can write a function this way:

int sumOnePlusOne() {
 return (1+1);
}

but what happens if I want sum up 1 + 2? I’ll need to create another function. So, instead I can create a generic one like this

sumTwoNumbers(int number1, int number2) { 
 return (number1 + number2);
}

and whenever I need to sum two numbers I can call this generic function and pass the values I want to sum as variables.

int theSum = sumTwoNumbers(3,15);

3 Likes

I was just about to ask the same thing!
Thanks!

@rocamargo I had a similar question, and I think what they’re getting at is, why not just create member variables that can be used in all functions rather than passing them around?

So in your example, why not just have int number1 and int number2 declared as member variables? If they’re being passed around, it clearly means they’re being used in more than one function. So why not?

1 Like

Because then they’re part of the class so add to the class’ size in memory and can’t be optimised away by the compiler. The optimiser can’t partially optimise away a class like that.

1 Like

That’s a poor choice, Halobob. When you have what is called as “global variables”, this is very hard to maintain the code. We may not know when exactly this variable will be changed and by who. So once you have a bad behavior it’s a nightmare to find who is updating, when, and where. That’s just good practice to declare small scopes and generalize as much as possible so you can see pretty clear where your problem is once it happens. I’m a Java developer for 20 years or so and I can tell you that for some small usage declaring member variables can be OK, but you need to know exactly why you’re doing this. In C++ you may also have the problems that DanM told us below.

1 Like

Gotcha, that makes sense. Thanks for the info!

Ahh, that makes sense. Thanks for the explanation!

That makes a whole lot of sense actually and admittedly that was what triggered this question for me since i’ve been using C# in unity for a while and I never saw the need to pass the variable through the function instead of just making it global. You do make a very good point on it being hard to track down variables and when they are changed like this though as i’ve had that problem a couple of times in the past, i’ll have to try applying this to my own code more often to get the hang of it.

Thank you for taking the time out to answer this and sorry for the late reply.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms