The idiom is more useful when you're writing a while loop instead of an if statement. For an if statement, you can break it up as you describe. But without this construct, you would either have to repeat yourself:
c = getchar();
while (c != EOF) {
// ...
c = getchar();
}
or use a loop-and-a-half structure:
while (true) {
c = getchar();
if (c == EOF) break;
// ...
}
I find it most useful in chains of actions which often involve error detection, etc.
if ((rc = first_check(arg1, arg2)) != 0)
{
report error based on rc
}
else if ((rc = second_check(arg2, arg3)) != 0)
{
report error based on new rc
}
else if ((rc = third_check(arg3, arg4)) != 0)
{
report error based on new rc
}
else
{
do what you really wanted to do
}
The alternative (not using the assignment in the condition) is:
rc = first_check(arg1, arg2);
if (rc != 0)
{
report error based on rc
}
else
{
rc = second_check(arg2, arg3);
if (rc != 0)
{
report error based on new rc
}
else
{
rc = third_check(arg3, arg4);
if (rc != 0)
{
report error based on new rc
}
else
{
do what you really wanted to do
}
}
}
With protracted error checking, the alternative can run off the RHS of the page whereas the assignment-in-conditional version does not do that.
The error checks could also be 'actions' — first_action(), second_action(), third_action() — of course, rather than just checks. That is, they could be checked steps in the process that the function is managing. (Most often in the code I work with, the functions are along the lines of pre-condition checks, or memory allocations needed for the function to work, or along similar lines).
Take an example: There is a method someMethod() and in an if condition you want to check whether the return value of the method is null. If not, you are going to use the return value again.
If(null != someMethod()){
String s = someMethod();
......
//Use s
}
It will hamper the performance since you are calling the same method twice. Instead use:
String s;
If(null != (s = someMethod())) {
......
//Use s
}