Adam
Adam

Reputation: 10016

Variable passed to a function giving unexpected value

When I pass an integer to the function below via a variable (ie x=1 PrintAccntInfo( x, bank_name) it is always read as 0 by the function regardless of its actual value. However, if I type in the value directly ie PrintAccntInfo(1, bank_name) the function works fine. Can someone explain to me what is going on here? Thanks!

void Bank::PrintAccntInfo(int accntnum, Bank bank_name) {
    int num_transactions = 0;
    transaction_node *temp;
    temp = bank_name.accounts[accntnum].head;
    .......

accntnum is the problem.

Edit:

Here is the code I call the function from (resp is a string read in from the user):

    if (stoi(resp)) {
                        int resp_int = stoi(resp);

                        if (resp_int = 0) {
                            for (int i=1;i<21;i++)  //print all the account transactions                    
                                PrintAccntInfo(i,our_bank);
                            badinputchk = false;
                        } else {
                            PrintAccntInfo(resp_int,our_bank);
                            badinputchk = false;
                        }
    }

Upvotes: 0

Views: 125

Answers (3)

Alexey Teplyakov
Alexey Teplyakov

Reputation: 316

The reason why you always get 0 in function is that condition

if (resp_int = 0)

sets resp_int to 0 and evaluates to false, so it always goes inside "else" where the function is invoked with resp_int(which is 0)

You should replace it with if (resp_int == 0)

Upvotes: 3

kfsone
kfsone

Reputation: 24249

Be aware that variables have "scope".

int i = 10;

int func(int i) {
    if (i > 0) {
       int i = 23 + i;
       std::cout << "inside func, inside the if, the i here is " << i << std::endl;
    }
    return i;
}

int main() {
    int i = 15;
    if (i == 15) {
        int i = func(100);
        std::cout << "in this part of main, i is " << i << std::endl;
    }
    std::cout << "But in the end, the outer i is " << i << std::endl;
}

Upvotes: 0

Sameera
Sameera

Reputation: 304

I think the value of the x is out of the scope. It's better you can show how do you call the function PrintAccntInfo() and the definition of the x.

Upvotes: 0

Related Questions