You could write the second statement as;
int tmp;
...
tmp = close(fd);
if(tmp == -1)
errExit("close");
But since tmp
serves no purpose after the check in the if
(and a good compiler will indeed optimise it away), it has the same effect if you write it as the original code.
On the other hand, we can use assignments in if-statements, so:
if ((fd = shm_open(argv[1], O_RDWR_O)) == -1)
errExit("shm_open");
will also work.
The key here is that the first one does indeed store a value that we want to use later (if successfully opening the shared memory), so it's clearer to write it as two separate statements, rather than "hiding" it in the if-statement.
On the other hand, in the second case, we have no use for the result of close
, so there's no purpose to writing an extra line and have an extra variable.