your problem is the variable
sumOfValues
inside the declaration of the function
multipleCheck
as you said but I think that we should step back for a moment and analyze your code.
you are declaring a global variable here
int sumOfValues = 0;
you are declaring another variable named
sumOfValues
inside your
multipleCheck
function.
there is nothing in the C++ standard that says that you can't create 2 variable in 2 different scopes with the same name, you will just end up having 2 separate variable with the same name, your real problem is the fact that the assignment operator
=
operates from right to left and the
+
operator for the addition got the same right-to-left precedence.
you should visualize the situation this way:
- the compiler goes on that line
- it finds an equal sign
=
- it starts analyzing what is on its right first ( because of the precedence rule )
- if finds a
+
sign and again, what is on its right should be considered first than anything else
- the
+
sign cares about the value of your variable, simply because it got an arithmetic addition to do, but on the right there is a variable that is not initialized yet, and to be picky, that variable it's not even created ( remember that what is on the left of the
=
it's not even considered yet by the compiler because of all the precedence rules ).
the
fix is really simple in this case
int sumOfValues = i+sumOfValues;
should be
sumOfValues = i+sumOfValues;
and in this case you are using the first global variable sumOfValues that you have declared in your code, to use a local variable in that function you should write
1 2 3 4 5
|
void multipleCheck(int i)
{
int sumOfValues = 0 ;
...
}
|
but this actions are fixing your problem with that line, your code still contains relevant errors, since you are learning that I'm not sure if it's best for you to have someone else writing the program for you but next time, to prevent errors like this, it's important to focus on :
- global and local variables
- operators and their own precedence