Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Assignment in an "IF" statement

Status
Not open for further replies.

Muskaan

Programmer
Oct 21, 2002
47
US
It is not common practice to code an assignment in an if expression i.e. if (a = 3) would assign a the value 3 and since 3 != 0, the expression is evalutated to TRUE.

But in some cases it does help to do that:

char fieldName[4];

if (ana.empty() && strcpy(fieldName,"ana") ||
cna.empty() && strcpy(fieldName,"cna") ||
fmt.empty() && strcpy(fieldName,"fmt") )
{
cout << &quot;Required Field not populated: &quot; << fieldName << endl;
}

The intent of the above code is to evaluate only until it comes across an empty field, and assign that empty field name to variable fieldName.

I want to know if this is do-able. Does anyone foresee problems with this code ? I know I am putting an assignment in an if statement, and it may not be advisable. Why would it be incorrect to do so ?

I would need to write the same code in a more complex if- else construct if I did not follow this solution. Anyone has better ideas ?
 
It is just from a maintenance point of view. You will need someone who remembers the order of precedence for || and &&. For someone like myself (and three-quarters of the programmers I know), I normally add in brackets because I can never remember whether || or && has higher precedence. I'd have to turn to page 52 of K&R.

The only problem I can see is that if ana and fmt are empty, it would stop at ana but would miss out fmt. An alternative is the shell programmers trick of

ana.empty() && strcpy(fieldName,&quot;ana&quot;) && cout << &quot;Required Field not populated: &quot; << fieldName << endl;
cna.empty() && strcpy(fieldName,&quot;cna&quot;) && cout << &quot;Required Field not populated: &quot; << fieldName << endl;
fmt.empty() && strcpy(fieldName,&quot;fmt&quot;) && cout << &quot;Required Field not populated: &quot; << fieldName << endl;

This uses the third && as the then part of the if-then else. Probably be even more confusing for the inexperienced programmers.
 
hi muskaan ..

there are more than one ways to solve any problem. your conditional construst will do the trick for what you require right now.

if in the future you think this is not okay/appropriate/correct, you will automatically look forward to another solution.

so, there is nothing wrong in what you have done right now.

br:
 
hi xwb and jmnagi,
thanks for the response! My code works alright with the previous code. Since you don't see problems with it, I think I will continue with the same. Xwb, I do intend to stop at the first empty field. Thanks, Muskaan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top