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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Question about if statment

Status
Not open for further replies.

MinnisotaFreezing

Programmer
Jun 21, 2001
120
KR
Hey,

I have written and seen if statments writen both of the following ways:

CString string = "Happy";
if (string.GetLength() != 0)
DoSomthing

and

if (int ret = string.GetLength() != 0)
DoSomthing

As far as I can tell, they both work the same way, but it seems like MSDN prefers the second way. I like the first because it is shorter. Any arguments for or against either one?

CJB
 
The first one is better because you don't have to allocate and assign an supplementary int value.

However, the second for is more often used in other statements where it helps claryfing the code:

if(TRUE == (IsThisNumber2()== 2)) ....

or in COM in comparison with constant like NOERROR, E_FAIL and so on...

HTH, s-)

Blessed is he who in the name of justice and goodwill, sheperds the weak through the valley of darkness...
 
In the second case, you can have:

if( (int ret = string.GetLength())!= 0 )
{
do something using ret instead of calling GetLength again
}

That's what is usefull in that case.

Vincent
 
Of course, ret will always be 1, which is maybe not so useful:)

More sensible is maybe

if (int len = string.GetLength())

where you have the string length in len...
:) Hope that this helped! :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top