how to pass variables in function parameters

I've learned that using non-const variables in file namespace is bad practice (and of course I don't want to develop bad habits). However, I'm not sure how I'm supposed to pass my variables through to other functions without putting them in file namespace and I can't find any solid examples or explanations anywhere.
example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  int add();

int main()
{
	int input1, input2;
	std::cin >> input1;
	std::cin >> input2;
	add();

	std::cout << total << std::endl;

	system("pause");
        return 0;
}

int add()
{
	int total = input1 + input2;
	return total;
}


How do I get add() to know about input1 and input2 without putting them in file namespace?

Thanks in advance :)
Last edited on
int add(int input1, int intput2)

Now:

int total = add(input1, input2);
std::cout << total << std::endl;
When putting this into practice I'm getting several errors:
error C4700: uninitialized local variable 'isRunning' used
error C4700: uninitialized local variable 'difficulty' used
error C4700: uninitialized local variable 'score' used

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include "stdafx.h"
#include <iostream>
#include <Windows.h>
#include <conio.h>
#include "main.h"

int main()
{
	int score, difficulty;
	bool isRunning;

	Setup(score, difficulty, isRunning);
	while (isRunning = true)
	{

	}
    return 0;
}


but all of my variables are initialized?

I'd guess that your setup function is being given copies of the variables score, difficulty, isRunning. Anything it does, it does with those copies. The originals in the function main are unchanged.

If you pass-by-value, you pass copies.
http://www.learncpp.com/cpp-tutorial/72-passing-arguments-by-value/


If you pass-by-reference, the function operates on the original variables; not on copies.
http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/
Last edited on
How do I get add() to know about input1 and input2 without putting them in file namespace?

See function addition(). The first example in the tutorial page:
http://www.cplusplus.com/doc/tutorial/functions/
Ah, I havent gotten to that chapter on learncpp yet so that should help
Ok thanks! Got it down now everything is working as expected!

the learncpp chapter was a bit confusing so i found a good youtube video that explained it well

https://www.youtube.com/watch?v=fCAaAIYpdA4
Last edited on
Topic archived. No new replies allowed.