C++ Undefined error please help me.

I'm pretty sure my entire code is fine! This is a very basic code because i am just starting to learn C++ and am making a very basic calculator. Please review this and let me know what issues there could possibly be!!!
It states the "sum" is undefined within my PosNeg function on the very bottom. This is also being done in code blocks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
  
#include <iostream>

using namespace std;

void PosNeg();

int main(){

    PosNeg();

    int a;
    int b;
    int sum;
    sum = a + b;

    cout << "Basic Calculator Trial \n " "Input a number, Dragon!" << endl;
    cin >> a;
    cout << " Enter another!" << endl;
    cin >> b;



    cout << " The total is " << sum << endl;
}

void PosNeg(){

if(sum>0)
    cout << "This number is a positive!" << endl;

if(sum<0)
    cout<< "This number is a negative!" << endl;
}
Last edited on
PosNeg has no idea of what 'sum' is because 'sum' is defined inside main, but PosNeg cannot access main's scope.
What you want is probably to make PosNeg take a parameter.

Line 15 is no good. Since 'a' and 'b' are not initialized until line 18, when the addition executes they have undefined values, leading to 'sum' being undefined too.
As maeriden says, you need to think about the order of events. there's no point adding 2 numbers up if you don't (at that moment in time) know what the 2 numbers are.
consider moving your line 15 down to line 21 (i.e. once you know the numbers).

Also move line 10 down to after line 24 and change your function signature to:
void PosNeg(int sum)
Last edited on
Thank you I solved it by moving my PosNeg() to line 23ish under the final text of my main function and adding (int sum) into both void paramaters then adding sum into the PosNeg(sum) prototype. Thank you. Now I can continue learning!
Last edited on
I hope you meant that you can continue learning :)
Yes stupid phone auto correct XD. I edited. Thanks
Again eveyone!
Topic archived. No new replies allowed.