Alright, so I'm wondering how I can check whether one variable is ASSIGNED to another variable (as in, statement is true if Var A is assigned to var B). However, I cannot simply say if(varA==varB) because in my program, varA could also be equal to varC, which has an if statement as well and would ruin everything. Any help?
variables do not hold assignment information. They only hold a value.
1 2 3 4 5 6 7 8 9 10
int A = 5;
int B = 6;
B = A; // here, A's value gets stored in B
// since A was 5, this means that now B is 5
// at this point, the only thing B knows is that it contains 5. It does not
// know that the 5 came from A. There is no way to check whether or not
// A was assigned to B or vice versa.
If you want a variable that contains another variable (and not just a value), then maybe you want a pointer... but as Framework said this is very strange:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int A = 5;
int* B = nullptr; // B points to nothing
int C = 5;
// make B point to A
B = &A;
// now B == &A, so you can use that to check whether or not that
// assignment occurred:
if(B == &A)
{
// will execute
}
if(B == &C)
{
// will not execute, even though A==C
}
Thanks guys I'll try to post a simplified version of what I'm doing.
char x;
float varA=0, varB=0, varC, amount;
cout<<"Enter a or b:";
cin>>x;
if(x=='a')
varC=varA;
else if(x=='b')
varC=varB;
cout<<"Enter the amount to add or subtract:";
cin>>amount;
*** if(varC==varA)
varC+=amount;
***else if(varC==varB)
varC-=amount;
The lines marked with asterisks are where I'm having a problem, because both statements will be true since both A and B are set to zero initially. (The first "if" is used, the "else if" gets overridden.)
Also, the value of x gets changed in other spots of my program so I can't use if(x=='a') etc. again. And I have to have both values set to zero initially. So any help?
instead of if(varC==varA) do if(x=='a') and the else if (x=='b') and proceed as you've done.
You already have x which appears to be your "condition", reuse it.
Also, I know this is a small program, but I'd suggest using meaningful names for all variables whenever you can, if not for anything other than making it habit.
char x;
float varA=0, varB=0, amount;
float* varToUse = nullptr;
cout<<"Enter a or b:";
cin>>x;
if(x=='a')
varToUse = &varA;
elseif(x == 'b')
varToUse = &varB;
else
/* give some kind of error to the user and abort */
cout<<"Enter the amount to add or subtract:";
cin>>amount;
// no need to do any more 'ifs' here, just use the pointer
*varToUse += amount; // this will modify varA or varB depending on which
// one it points to.