A question about variable assignment...

In my program, if I assign my variable in same line, my program doesn't work.

 
int foo = myFunction();


whereas if I assign my variable in second line, it works.

1
2
int foo;
foo = myFunction();


What's the difference?
The first is not assignment, but initialization.

However, it is impossible to say without more context why there would be observable difference.

Besides. "doesn't work" doesn't tell what doesn't work. There are many different ways that things "do not work", and if you don't tell the details neither we nor you can diagnose the issue.
my whole code

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
#include <iostream>
#include <fstream>

using namespace std;


int getInput();


int main(){
    int input;
    input = getInput();
    
    while(input != 4){
        
        int input = getInput();
    }

    return 0;
}

int getInput(){
    int choice;
    
    cout << "1 - current items" << endl;
    cout << "2 - helpful items" << endl;
    cout << "3 - harmful items" << endl;
    cout << "4 - quit" << endl;
    
    cin >> choice;
    return choice;
}


Somehow I fixed variable error but now I have a new problem. When my program starts, and I press 4, it quits. But when my program starts and I press other numbers first and then press 4, It won't quit.

I have a no idea what's going on.
The input on line 14 is the input declared on line 11.
Line 16 declares a different input.
I don't understand what you're trying to say.


this code is from Bucky's tutorial and his code works perfectly fine.

https://www.youtube.com/watch?v=Xb-ae2NEGRs&index=68&list=PLAE85DE8440AA6B83
Last edited on
this code is from Bucky's tutorial

No, it is not. Your copy is not accurate.

Here is another main() that is practically identical to yours:
1
2
3
4
5
6
7
8
9
10
11
int main(){
    int input;
    input = getInput();
    
    while(input != 4){
        
        int fubar = getInput();
    }

    return 0;
}

Can you see the difference between Bucky's and the above code?
Topic archived. No new replies allowed.