single if vs if else

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Chad

    single if vs if else

    The question stems from some code at the following url



    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.
  • Ben Pfaff

    #2
    Re: single if vs if else

    Chad <cdalten@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

    Comment

    • Chad

      #3
      Re: single if vs if else

      On Jun 25, 7:58 pm, Ben Pfaff <b...@cs.stanfo rd.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.

      Comment

      • CBFalconer

        #4
        Re: single if vs if else

        Chad wrote:
        >
        The question stems from some code at the following url
        >

        >
        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.b in, "rb"))) {
        fputs("File error", stderr);
        exit(EXIT_FAILU RE);
        }

        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 **

        Comment

        • Mike Wahler

          #5
          Re: single if vs if else


          "Chad" <cdalten@gmail. comwrote in message
          news:46512086-5c36-4933-bb49-6130b9f90a20@p2 5g2000pri.googl egroups.com...
          The question stems from some code at the following url
          >

          >
          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


          Comment

          • rahul

            #6
            Re: single if vs if else

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

            >
            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.

            Comment

            • CBFalconer

              #7
              Re: single if vs if else

              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 **

              Comment

              • Stephen Sprunk

                #8
                Re: single if vs if else

                Chad wrote:
                On Jun 25, 7:58 pm, Ben Pfaff <b...@cs.stanfo rd.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

                Comment

                • pete

                  #9
                  Re: single if vs if else

                  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((unsign ed char)*s1);
                  const int c2 = tolower((unsign ed char)*s2);

                  if (c2 != c1) {
                  return c2 c1 ? -1 : 1;
                  }
                  } else {
                  if (*s1 == '\0') {
                  return 0;
                  }
                  }
                  ++s1;
                  ++s2;
                  }
                  }


                  --
                  pete

                  Comment

                  • Walter Roberson

                    #10
                    Re: single if vs if else

                    In article <88O8k.6711$cW3 .3757@nlpi064.n bdc.sbc.com>,
                    Stephen Sprunk <stephen@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

                    Comment

                    • Stephen Sprunk

                      #11
                      Re: single if vs if else

                      Walter Roberson wrote:
                      In article <88O8k.6711$cW3 .3757@nlpi064.n bdc.sbc.com>,
                      Stephen Sprunk <stephen@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

                      Comment

                      • Thad Smith

                        #12
                        Re: single if vs if else

                        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

                        Comment

                        Working...