473,796 Members | 2,658 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Recommended style

Hi all,

Which is the recommended style in production code for the following -

....
fp = fopen("xyz.txt" , "r");
if (fp == NULL) {
....
}

OR
fp = fopen("xyz.txt" , "r");
if (!fp) {
....
}

Thanks.

Nov 14 '05
62 2610
vir
Mike Wahler wrote:
"Emmanuel Delahaye" <em***@YOURBRAn oos.fr> wrote in message
news:mn******** *************** @YOURBRAnoos.fr ...
Victor Nazarov wrote on 01/01/05 :
I usually use this:

{
fp = fopen (fn, fmode);
if (!fp) {
error ();
goto fail;
}
rc = foo (fp);
fail:
if (!fp)
fclose (fp);
}


Isn't it a little bit complicated for the purpose ? Or is it a troll ?

Probably a troll. Note the OP's "name".

What's wrong with the name?

This style is to be used for a functions allocating several resources...
Think of

int foo (int len)
{
FILE *f1p = NULL, *f2p = NULL;
char *s = NULL;
int res = -1;

f1p = fopen (fn, fmode);
if (!f1p) {
error ();
goto fail;
}
f2p = fopen (fn, fmode);
if (!f2p) {
error ();
goto fail;
}
s = malloc (len);
if (!s) {
error ();
goto fail;
}
/*
...
Some valuable actions
...
*/
res = 0
fail:
free (s);
if (!f2p)
fclose (f2p);
if (!f1p)
fclose (f1p);
return res;
}

Cascaded function calls seems to be less readable then one function.

--
vir
Nov 14 '05 #51
"Herbert Rosenau" <os****@pc-rosenau.de> wrote in message
news:wm******** *************** ****@URANUS1.DV-ROSENAU.DE...
On Sun, 2 Jan 2005 08:46:10 UTC, Michael Mair
<Mi**********@i nvalid.invalid> wrote:
if (!x) or in long if (x != 0)


if (!x) is equivalent to if (x == 0)


No, it's not, it is highly different.


Really?

ISO 9899:1999

6.5.3.3 Unary arithmetic operators

5 The result of the logical negation operator ! is 0
if the value of its operand compares unequal to 0,
1 if the value of its operand compares equal to 0.
The result has type int. The expression !E is
equivalent to (0==E).
-Mike
Nov 14 '05 #52
Lawrence Kirby quoted:
if((fp=fopen (filename,"mode "))==NULL)

and commented
That's a clear, concise C idiom, but please locate your space bar.
LK again quoted:
if ( NULL == ( fp = fopen( filename, mode ) ) ) {


and commented:
Whereas that's just contorted. The point of space is to help the eye see
the natural grouping. Put space around everything and you're no better of
than not using spaces at all, perhaps worse.


Agreed, absolutely. If I were writing the first of these examples I
would write

if ((fp = fopen(filename, "mode")) == NULL)

and if I were writing the second,

if (NULL == (fp = fopen(filename, mode))) {

BUT... if I were writing for comprehensibili ty I would eschew both
and write:

fp = fopen(filename, "mode");
if (fp == NULL) {
/* respond to error condition */

There's just too great an opportunity for error in the "cutesy"
versions of this code, which roll the basic assignment into the
detection of an error condition. The immature programmer thinks,
"Look how smart I am, how many things I can do at once!". The
mature programmer thinks, "Let's do one thing at a time, in such
a way that it's quite transparent what we're doing; and let's
get it RIGHT."

IMO.

Allin Cottrell


Nov 14 '05 #53

In article <cr***********@ news.comcor-tv.ru>, vir <vv*****@mail.r u> writes:

This style is to be used for a functions allocating several resources...
Think of

int foo (int len)
{
FILE *f1p = NULL, *f2p = NULL;
char *s = NULL;
int res = -1;

f1p = fopen (fn, fmode);
if (!f1p) {
error ();
goto fail;
}
...
fail:
free (s);
if (!f2p)
fclose (f2p);
if (!f1p)
fclose (f1p);
return res;
}
I also use this single-point-of-return style (though I employ it
slightly differently) in many cases, and consider it the most
prominent excuse for employing goto, as those who remember our
most recent "goto" flame war know. However, note that
if (!f2p)
fclose (f2p);
if (!f1p)
fclose (f1p);


should be

if (f2p)
fclose (f2p);
if (f1p)
fclose (f1p);

since obviously you want to call fclose only if the FILE* variable
is NOT null. And that, I suppose, demonstrates that correctness
still trumps style.

(Personally, I wish the committee had defined behavior for null
arguments for fclose and some of the other functions, as they did
for free, if only to get rid of those guard if's. But we have the
language we have.)

--
Michael Wojcik mi************@ microfocus.com

When most of what you do is a bit of a fraud, the word "profession "
starts to look like the Berlin Wall. -- Tawada Yoko (t. M. Mitsutani)
Nov 14 '05 #54
Victor Nazarov wrote:

I usually use this:

{
fp = fopen (fn, fmode);
if (!fp) {
error ();
goto fail;
}
rc = foo (fp);
fail:
if (!fp)
fclose (fp);
}


Stylish, indeed! It verges upon the elegant! There
is, however, one tiny drawback: It's wrong.

"Other than that, Mrs. Lincoln, what did you think
of the play?"

--
Er*********@sun .com
Nov 14 '05 #55
Eric Sosman <er*********@su n.com> writes:
Victor Nazarov wrote:

I usually use this:

{
fp = fopen (fn, fmode);
if (!fp) {
error ();
goto fail;
}
rc = foo (fp);
fail:
if (!fp)
fclose (fp);
}


Stylish, indeed! It verges upon the elegant! There
is, however, one tiny drawback: It's wrong.


It can be made correct by deleting one character.
--
"I should killfile you where you stand, worthless human." --Kaz
Nov 14 '05 #56
Ben Pfaff wrote:
Eric Sosman <er*********@su n.com> writes:
Victor Nazarov wrote:
I usually use this:

{
fp = fopen (fn, fmode);
if (!fp) {
error ();
goto fail;
}
rc = foo (fp);
fail:
if (!fp)
fclose (fp);
}


Stylish, indeed! It verges upon the elegant! There
is, however, one tiny drawback: It's wrong.


It can be made correct by deleting one character.


Or by repeating it, if "deleting a character" is
too gruesome in the context of the play (a remark your
good taste, er, deleted ...)

This sort of mistake is, I think, a good reason
to prefer `x == 0' (or `0 == x' if a backward-thinking
person you are, young Skywalker) over `!x' when `x'
isn't "obviously boolean." I particularly dislike

if (!strcmp(passwo rd, "drowssap") )

.... which tests for equality but appears on a hasty
reading to do the opposite.

--
Er*********@sun .com

Nov 14 '05 #57
vir
Michael Wojcik wrote:
In article <cr***********@ news.comcor-tv.ru>, vir <vv*****@mail.r u> writes:
This style is to be used for a functions allocating several resources...
Think of

int foo (int len)
{
FILE *f1p = NULL, *f2p = NULL;
char *s = NULL;
int res = -1;

f1p = fopen (fn, fmode);
if (!f1p) {
error ();
goto fail;
}
...
fail:
free (s);
if (!f2p)
fclose (f2p);
if (!f1p)
fclose (f1p);
return res;
}

I also use this single-point-of-return style (though I employ it
slightly differently) in many cases, and consider it the most
prominent excuse for employing goto, as those who remember our
most recent "goto" flame war know.

I havn't read the thread about goto. But if I get read of goto statement
I'll need an exception mechanism in C...
However, note that

if (!f2p)
fclose (f2p);
if (!f1p)
fclose (f1p);

should be

if (f2p)
fclose (f2p);
if (f1p)
fclose (f1p);

since obviously you want to call fclose only if the FILE* variable
is NOT null.

Yes, sorry for this mistake.
And that, I suppose, demonstrates that correctness
still trumps style.

(Personally, I wish the committee had defined behavior for null
arguments for fclose and some of the other functions, as they did
for free, if only to get rid of those guard if's. But we have the
language we have.)

Agread. In my own code I allways write destructors accepting invalid
value (NULL in most cases).

--
vir
Nov 14 '05 #58
Andrey Tarasevich wrote:

Kelvin Moss wrote:
Which is the recommended style in production code for the following -

...
fp = fopen("xyz.txt" , "r");
if (fp == NULL) {
...
}

OR
fp = fopen("xyz.txt" , "r");
if (!fp) {
...
}
...


It is a matter of a personal preference and/or coding standard.

Personally, I leave out explicit comparison for values with pronounced
'boolean' semantics only. All other values require explicit comparison
in my book. That would mean that I'd choose the first variant.


Me too.
Nov 14 '05 #59

In article <cr**********@n ews1brm.Central .Sun.COM>, Eric Sosman <er*********@su n.com> writes:
Victor Nazarov wrote:

if (!fp)
fclose (fp);

This sort of mistake is, I think, a good reason
to prefer `x == 0' (or `0 == x' if a backward-thinking
person you are, young Skywalker) over `!x' when `x'
isn't "obviously boolean."


I'm not convinced that would significantly reduce this sort of error.
I strongly doubt it would for me (though I can't recall having made
this particular mistake; doesn't mean I haven't, but it hasn't happened
often or recently enough for me to remember). I don't find the
comparison with an explicit zero any more readable than the logical-
negation one, or see any other reason why it might discourage error.

But, of course, YMMV.
I particularly dislike

if (!strcmp(passwo rd, "drowssap") )

... which tests for equality but appears on a hasty
reading to do the opposite.


With this, on the other hand, I agree. Inverted strcmp sense errors
are one of the more common sort I find in others' code. I don't
remember making one myself since I adopted Peter van der Linden's
macro, which I think does improve readability significantly. For
example:

#define MySTRCMP(s1, op, s2) (strcmp(s1, s2) op 0)
if (MySTRCMP(passw ord, ==, "drowssap") )

Inlining the operator brings string comparisons syntactically closer
to their numeric cousins.

--
Michael Wojcik mi************@ microfocus.com

An intense imaginative activity accompanied by a psychological and moral
passivity is bound eventually to result in a curbing of the growth to
maturity and in consequent artistic repetitiveness and stultification.
-- D. S. Savage
Nov 14 '05 #60

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1801
by: mikeg | last post by:
Hi, I'd like to explicitly link to the recommended php.ini file. For a long time, this link worked: http://cvs.php.net/co.php/php4/php.ini-recommended (In fact, if you google for "php ini recommended", that broken link comes up first).
6
2264
by: Huy | last post by:
Generic PHP newbie question here. May anyone please recommend books that have gotten you started on PHP (interfacing with MySQL is a plus) & also reference books? Just looking for some good quality books to purchase.
13
2396
by: Michele Simionato | last post by:
What is the recommended way of generating HTML from Python? I know of HTMLGen and of few recipes in the Cookbook, but is there something which is more or less standard? Also, are there plans to include a module for HTML generation in the standard library? I really would like to see some standardization in this area. Michele Simionato
7
4392
by: Mike Kamermans | last post by:
I hope someone can help me, because what I'm going through at the moment trying to edit XML documents is enough to make me want to never edit XML again. I'm looking for an XML editor that has a few features that you'd expect in any editor, except nearly none of them seem to have: 1 - Search and repalce with Regular Expressions. 2 - Search and Replace in an Xpath context. 3 - User specified tag-generation for either on a...
22
5151
by: Jonathan Snook | last post by:
I've been contemplating what the recommended usage of a "top of page" link should be? Should there only ever be one at the bottom of the page? Should they be sprinkled at various points on the page? Or should they be used at all? Lately, I've been leaning towards the last option because my thought is that most browsers have a method to make it back to the top of the page (home button, scroll bar, whatever). It seems I never use the...
11
1643
by: G Patel | last post by:
Can anways explain why many multi-file programs I've seen don't have a main.c file, instead main() is hidden in a file with a different name? Is this just a preference, or is there an unspoken rule (or advantage). I've been calling the file with main, main.c, and I was wondering if there are any caveats against this (that might prevent me from being laughed at or something).
3
1778
by: darren via AccessMonster.com | last post by:
Hi I'm based in the UK and I've drifted into Access from building a simple db for myself, to then being asked to build a simple db for someone else, to now spending time building increasingly more sophisticated (for me)databases. So far my learning curve has been based upon a handleful of books and this forum (which I think is fantastic and the level of help and knowledge sharing has astounded me). Aside from the very basic dummies...
2
15497
by: Mark Rae | last post by:
Hi, I've been asked to "update" an existing fairly simple website to make it XHTML-compliant i.e. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > ... </html>
13
2106
by: Michael M. | last post by:
In Perl, it was: ## Example: "Abc | def | ghi | jkl" ## -"Abc ghi jkl" ## Take only the text betewwn the 2nd pipe (=cut the text in the 1st pipe). $na =~ s/\ \|(.*?)\ \|(.*?)\ \|/$2/g; ## -- remove in text
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9533
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10461
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10190
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10019
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7555
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6796
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5579
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3736
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.