By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,391 Members | 1,387 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,391 IT Pros & Developers. It's quick & easy.

single if vs if else

P: n/a
The question stems from some code at the following url

http://www.cplusplus.com/reference/c...dio/fread.html

In the code example they have a single if statement for the following

pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
Why use a single if statement as opposed to if-else? Just curious
because I see this appear a lot in C code. Ie a single if statement vs
using if-else.
Jun 27 '08 #1
Share this Question
Share on Google+
11 Replies


P: n/a
Chad <cd*****@gmail.comwrites:
pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
Why use a single if statement as opposed to if-else? Just curious
because I see this appear a lot in C code. Ie a single if statement vs
using if-else.
I think that you are, roughly speaking, comparing the following:
A;
if (B) {
C;
exit(1);
}
D;
against this:
A;
if (B) {
C;
exit(1);
} else {
D;
}

Many programmers would prefer the former because D, which is the
entire rest of the function, is not indented as far to the
right. Pushing code far to the right in this case wastes
horizontal space without much benefit that I can see.
--
"C has its problems, but a language designed from scratch would have some too,
and we know C's problems."
--Bjarne Stroustrup
Jun 27 '08 #2

P: n/a
On Jun 25, 7:58*pm, Ben Pfaff <b...@cs.stanford.eduwrote:
Chad <cdal...@gmail.comwrites:
pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
Why use a single if statement as opposed to if-else? Just curious
because I see this appear a lot in C code. Ie a single if statement vs
using if-else.

I think that you are, roughly speaking, comparing the following:
* * * * A;
* * * * if (B) {
* * * * * * * * C;
* * * * * * * * exit(1);
* * * * }
* * * * D;
against this:
* * * * A;
* * * * if (B) {
* * * * * * * * C;
* * * * * * * * exit(1);
* * * * } else {
* * * * * * * * D;
* * * * }

Many programmers would prefer the former because D, which is the
entire rest of the function, is not indented as far to the
right. *Pushing code far to the right in this case wastes
horizontal space without much benefit that I can see.
--

Yes, the question was poorly worded. I still have *issues* making
myself clear. Anyhow, I thought that there was maybe something more
going on. Ie maybe there was some kind of broader concept at work.
Jun 27 '08 #3

P: n/a
Chad wrote:
>
The question stems from some code at the following url

http://www.cplusplus.com/reference/c...dio/fread.html

In the code example they have a single if statement for the following

pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

Why use a single if statement as opposed to if-else? Just curious
because I see this appear a lot in C code. Ie a single if statement vs
using if-else.
Simpler code is:

if (!(pFile = fopen("myfile.bin, "rb"))) {
fputs("File error", stderr);
exit(EXIT_FAILURE);
}

Note that exit(1) is not portable. No else is needed, because on
failure the program does not continue.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #4

P: n/a

"Chad" <cd*****@gmail.comwrote in message
news:46**********************************@p25g2000 pri.googlegroups.com...
The question stems from some code at the following url

http://www.cplusplus.com/reference/c...dio/fread.html

In the code example they have a single if statement for the following

pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
Why use a single if statement as opposed to if-else? Just curious
because I see this appear a lot in C code. Ie a single if statement vs
using if-else.
It depends upon the logic you want to implement. Contrast
the two following snippets:

=====================
if(x)
f1();
else
printf("message");

f3();
=======================

and

=========================
if(x)
f1();

printf("message");
f1();
=========================

In the first case "message" is only wanted when
'x' is false, in the second case, "message" is
always output.
In your example, all the error-reaction code is in the
'if' part. If there's no error, the 'else' is simply
to continue sequentially (rather than putting everything
else (sorry for pun) inside "else{}", which would be kinda
silly.

-Mike
Jun 27 '08 #5

P: n/a
On Jun 26, 7:43 am, Chad <cdal...@gmail.comwrote:
The question stems from some code at the following url

http://www.cplusplus.com/reference/c...dio/fread.html

In the code example they have a single if statement for the following

pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}

Why use a single if statement as opposed to if-else? Just curious
because I see this appear a lot in C code. Ie a single if statement vs
using if-else.
In your example, what is the else part going to be? if-else is used
when 2 way decision is to be made, if is used when the decision is to
be made on one condition; for multiple conditions we use switch/case
or if-else if ladders.

Jun 27 '08 #6

P: n/a
Nick Keighley wrote:
>
.... snip ...
>
*now* you must have the else. It has been argued that (a phrase
like that indicates I don't entirely agree...) it makes the program
easy to understand, reason about and debug (it may also prevent
cancer, world poverty and off-topic posts in comp.lang.c).
Cancer, world poverty - possibly. Off-topic posts - never. :-)

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #7

P: n/a
Chad wrote:
On Jun 25, 7:58 pm, Ben Pfaff <b...@cs.stanford.eduwrote:
>Chad <cdal...@gmail.comwrites:
>>pFile = fopen ( "myfile.bin" , "rb" );
if (pFile==NULL) {fputs ("File error",stderr); exit (1);}
Why use a single if statement as opposed to if-else? Just curious
because I see this appear a lot in C code. Ie a single if statement vs
using if-else.
I think that you are, roughly speaking, comparing the following:
A;
if (B) {
C;
exit(1);
}
D;
against this:
A;
if (B) {
C;
exit(1);
} else {
D;
}

Many programmers would prefer the former because D, which is the
entire rest of the function, is not indented as far to the
right. Pushing code far to the right in this case wastes
horizontal space without much benefit that I can see.
--


Yes, the question was poorly worded. I still have *issues* making
myself clear. Anyhow, I thought that there was maybe something more
going on. Ie maybe there was some kind of broader concept at work.
Some programmers prefer to have only a single return point from each
function; others prefer to return as soon as possible so that the
bypassed code does not have to be indented. It's a matter of style,
nothing more. The same debate applies to exit() as much as return.

S
Jun 27 '08 #8

P: n/a
Stephen Sprunk wrote:
Some programmers prefer to have only a single return point from each
function; others prefer to return as soon as possible so that the
bypassed code does not have to be indented. It's a matter of style,
nothing more. The same debate applies to exit() as much as return.
My rule is that it is bad to have an unnoticeable return
in the middle of a function.

A function consisting largely of return statements,
wouldn't violate that rule.

int str_cncmp(const char *s1, const char *s2, size_t n)
{
for (;;) {
if (n-- == 0) {
return 0;
}
if (*s1 != *s2) {
const int c1 = tolower((unsigned char)*s1);
const int c2 = tolower((unsigned char)*s2);

if (c2 != c1) {
return c2 c1 ? -1 : 1;
}
} else {
if (*s1 == '\0') {
return 0;
}
}
++s1;
++s2;
}
}
--
pete
Jun 27 '08 #9

P: n/a
In article <88*****************@nlpi064.nbdc.sbc.com>,
Stephen Sprunk <st*****@sprunk.orgwrote:
>Some programmers prefer to have only a single return point from each
function; others prefer to return as soon as possible so that the
bypassed code does not have to be indented. It's a matter of style,
nothing more.
It is also an issue with ease of proving program correctness.
That's "ease" rather than "ability": since the semantics of
the language are fixed, given a program with multiple returns and
permission to create temporary storage areas [not a certainty for
embedded programming], one can automatically transform the
multi-return program into a single-return program by adding state
variables.

The result might not be at all pretty, though. And it could change the
detailed behaviour of a real-time program -- which is more of an issue
than it might sound at first, because proof of behaviour (e.g., maximum
event execution time) for real-time programs can often be quite
important.
--
"Every intellectual product must be judged from the point of view
of the age and the people in which it was produced."
-- Walter Horatio Pater
Jun 27 '08 #10

P: n/a
Walter Roberson wrote:
In article <88*****************@nlpi064.nbdc.sbc.com>,
Stephen Sprunk <st*****@sprunk.orgwrote:
>Some programmers prefer to have only a single return point from each
function; others prefer to return as soon as possible so that the
bypassed code does not have to be indented. It's a matter of style,
nothing more.

It is also an issue with ease of proving program correctness.
That's "ease" rather than "ability": since the semantics of
the language are fixed, given a program with multiple returns and
permission to create temporary storage areas [not a certainty for
embedded programming], one can automatically transform the
multi-return program into a single-return program by adding state
variables.
An optimizing compiler, though, could transform either form to the other
reasonably easily under the hood, using the "as if" rule.

This:

int foobar(int condition) {
if (condition)
return FOO;
return BAR;
}

Might be transformed into this:

int foobar(int condition) {
int retval;
if (condition)
retval = FOO;
else
retval = BAR;
return retval;
}

or this:

int foobar(int condition) {
int retval;
if (condition) {
retval = FOO;
goto end;
}
retval = BAR;
end:
return retval;
}

They all do exactly the same thing, and the compiler is free to
transform any one of them into either of the others (or something else
entirely) as long as the result is the same. While these are trivial
examples and likely all perform the same even if translated literally
without much optimization, more complicated examples _could_ see size or
speed benefits from being transformed.

Still, the primary audience for source code is humans, not compilers.
Use of common style and idioms makes code easier to understand and
maintain, even if the compiler doesn't need them or transforms your code
into something else entirely (which runs faster, but equally correctly).
The result might not be at all pretty, though. And it could change the
detailed behaviour of a real-time program -- which is more of an issue
than it might sound at first, because proof of behaviour (e.g., maximum
event execution time) for real-time programs can often be quite
important.
Performance guarantees are outside the scope of the C standard, of
course. Proving correctness is a matter of logic; I'll submit that one
of the above constructions may be easier to prove correct than the
other, but proving which one is faster can only be done with empirical
testing. Thanks to modern optimizing compilers, it's virtually
impossible to guess which implementation of the same general algorithm
will be faster. For small values of N, it's not even possible to guess
which algorithm is fastest.

S
Jun 27 '08 #11

P: n/a
Stephen Sprunk wrote:
Performance guarantees are outside the scope of the C standard, of
course.
Yes.
Thanks to modern optimizing compilers, it's virtually
impossible to guess which implementation of the same general algorithm
will be faster.
I suppose that's true of an arbitrary compiler. Where the alternatives
matter, though, either know the compiler's behavior well before coding, or
look at the results of different code alternatives.
For small values of N, it's not even possible to guess
which algorithm is fastest.
If it not important, choose simple and easy. If it is important, don't guess.

--
Thad
Jun 29 '08 #12

This discussion thread is closed

Replies have been disabled for this discussion.