Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning the result of fopen inside an if statement

I am learning C currently and wanted to know whether the following two pieces of code perform differently, or if it's just a style thing.

Looking at some sources they the have the following code:

...
FILE * pFile;
pFile = fopen ("myfile.txt","r");
if (pFile == NULL)
{ some code }
...

While my professor has the following code in his notes:

...
FILE * pFile
if ((pFile = fopen("myfile.txt","r")) == NULL)
{ some code }
...

Just wanted to know if this is merely a style preference by different programmers or if there is an advantage to putting the return/set line inside the if statmeent.

like image 857
Peter Avatar asked Apr 29 '12 21:04

Peter


1 Answers

There is no difference. More experienced programmers sometimes go with the second form, just to save a line, but they are essentially identical. The second tends to be a little more "UNIX-y", where most function calls are checked for error (as opposed to success) before continuing.

like image 50
Jonathon Reinhart Avatar answered Sep 21 '22 13:09

Jonathon Reinhart