The code samples show you how you can process the returned value from a function without using a variable.
There are 2 things to look at here:
1) The printf() function returns the number of characters printed, or a negetive number if an error occurs. Almost everyone doesn't bother to access the returned value from printf(), but it exists.
2) The switch, while, and if statements don't use a semicolon at the end of the line.
So...
if(printf("Hello world")){
}
The IF line above is saying this: Use printf() to print out the text and if the returned value is not zero, execute the code between the { and } braces. As you can see, there is no code between the braces.
The IF line is an optimized way of checking the returned value from a function, without allocating a variable. If we used the IF statement in the regular way, we would have to do something like this:
int returned_value;
returned_value=printf("Hello world");
if (returned_value)
{
}
while(!printf("Hello world")){
}
The WHILE loop above is saying this: Use printf() to print out the text. If the returned value is zero (notice the "!" in front of printf), then continue executing the loop. In WHILE loops, the loop execution condition between the ( and ) is checked first, then the code between the { and } braces is executed. In this case, we have "while(!printf("Hello world"))", which means that the printf() function must execute FIRST, then the returned value is checked for zero. Writing the code this way saves us from having to allocate a variable beforehand, and then using that value to check for zero, like this:
int returned_value=1; /* allocate variable and set it to 1 so the while loop runs once */
while (!returned_value) /* check if returned_value is zero */
{
returned_value=printf("Hello world"); /* returned value from printf will NOT be zero */
}
The printf() function will only execute once, since it will return either a positive or negetive number --not zero.
In pseudocode:
1) printf()
2) If printf() returns zero, loop back to step 1
switch(printf("Hello world")){
}
Okay. You know how the SWITCH statement works, right? You will notice that there is no code between the { and } braces, so the printf() function will execute and that's it. The SWITCH statement does not contain any of the "case (some number):" labels between the braces.
You can also use the technique shown here when you call functions.
Example:
Let's say we have a procedure called foo() which returns a positive int value, and we want to use that returned value in a call to a procedure called foo2(), which takes 2 parameters.
Here's one way to do it:
unsigned int argh;
unsigned int argh2=4;
argh=foo();
foo2(argh, argh2);
Without allocating a variable to get the returned value from foo(), we could re-write the code like this:
foo2((foo(), argh2);