curlywei
curlywei

Reputation: 720

C: Call close() in if condition

Generally,

I read lot of code which always used following snippet to check if close fd successfully

// code A
int result = close(some_fd);
if ( result == -1)
  perror("close error");

I'd like to simplify above code

//code B
if ( close(some_fd) == -1 )
  perror("close error");

Above snippet can be executed and if has error,

then "close error" also can be display normally.

AFAIK, if (conditions) which conditions will be r-value,

so that should mean ( close(some_fd) == -1 ) just temporary

Dose close(some_fd) really execute normally when I call it in if condition?

Upvotes: 2

Views: 86

Answers (2)

Alberto Pires
Alberto Pires

Reputation: 319

Both are correct and are executed normally, you can use the first option if you need to use the return value from close() later, but it's only zero or -1, so in this case the second one is more practical.

Upvotes: 2

Marco Tizzano
Marco Tizzano

Reputation: 1916

You can safely invoke close inside the if.

In fact, you're a right when you say that the r-value is temporary, as it represents a value which is stored into a temporary memory address, just used to be assigned to a l-value.

However, in your case, what it's stored "temporarly" is the whole condition value, which means the return value of close(fd) fuction comparared to -1. Therefore, the close will be executed as expected, and its effects is not temporary.

Upvotes: 3

Related Questions