Question

What I saw in an if statement was like this.

if((var = someFunc()) == 0){
   ...
}

Will the statement

(var = someFunc()) 

always return the final value of var no matter what environment we are in?

Was it helpful?

Solution

That is just a one-line way of assigning to a variable and comparing the returned value at the same time.

You need the parentheses around the assignment because the comparison operators have higher precedence than the assignment operator, otherwise var would be assigned the value of someFunc() == 0.

OTHER TIPS

This is simply wrong. var is assigned, and then its value is overwritten by a constant 0. The return value of the function is therefore lost, and the if always fails. Most compilers would probably issue a warning about that nowadays, both because of the assignment within an if and because of the impossible if that results. The right way to do what was probably intended is

if((var = someFunc()) == 0) {

(Mind you, this might also be malicious code trying to introduce a vulnerability under the guise of a common newbie mistake. There was a case recently where someone tried to smuggle a check into the Linux kernel where they assigned the UID to 0 (i.e., root) while pretending to check for being root. Didn't work, though.)

This is correct, I use it all the time

if ((f=fopen(s,"r"))==NULL) return(fprintf(stderr,"fopen(%s,r) failed, errno=%d, %s\n",s,errno,strerror(errno))); /* successfully opened file s, read from FILE *f as you like */

I also use it when I calloc() memory.

You're assigning the return value of someFunc (fopen or calloc in my cases) to a variable AND also testing that return value, it's a semantic shortcut assuming you'll never want to debug the assignment and the test separately.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top