Variable declaration and initialisation

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

    #1

    Variable declaration and initialisation

    I just wanted to get some advice on what are the better practices:

    1) Should variables be declared at the beginning of a function or just
    before they are required?

    2) Should all variabled be initiailised immediately after declaration?

    Thanks

  • relient

    #2
    Re: Variable declaration and initialisation

    1.) Well, in c89 you don't have a choice. You must declare all your
    variables the the begining of the scope block. In c99, however, it's
    different. It's up to you to choose the best method, but, be
    consistent.

    2.) For safety reasons, you should, especially pointers. If you declare
    a poiner and don't intialize it to some non-null value; inititiaze it
    to null to avoid unwanted bugs in your code.

    That's my take on it.
    relient.

    Comment

    • osmium

      #3
      Re: Variable declaration and initialisation

      "James Brodie" writes:
      [color=blue]
      >I just wanted to get some advice on what are the better practices:
      >
      > 1) Should variables be declared at the beginning of a function or just
      > before they are required?[/color]

      They should be declared just before needed. The common form of C does not
      allow this, so it's a bit academic.
      [color=blue]
      > 2) Should all variabled be initiailised immediately after declaration?[/color]

      No. It just creates one more question in the mind of the person who must
      maintain the program. Why did he set this to 0? It creates an illusion of
      knowledge that doesn't exist.


      Comment

      • Keith Thompson

        #4
        Re: Variable declaration and initialisation

        "relient" <xllx.relient.x llx@gmail.com> writes:[color=blue]
        > 1.) Well, in c89 you don't have a choice. You must declare all your
        > variables the the begining of the scope block. In c99, however, it's
        > different. It's up to you to choose the best method, but, be
        > consistent.[/color]

        Even in C89/C90, you can declare variables at the beginning of any
        block, not just at the beginning of a function. For example:

        void func(void) {
        /* code that doesn't use x */
        {
        int x;
        /* code that uses x */
        }
        /* more code that doesn't use x */
        }
        [color=blue]
        > 2.) For safety reasons, you should, especially pointers. If you declare
        > a poiner and don't intialize it to some non-null value; inititiaze it
        > to null to avoid unwanted bugs in your code.[/color]

        On the other hand, I see a lot of code that initializes a variable,
        and then assigns a value to it before using it. A policy of *always*
        initializing every variable, whether the initial value is used or not,
        can avoid errors, but it's not always necessary.

        Also, it's important to provide some context when posting a followup.
        Google makes this unnecessarily difficult, but not impossible. See
        <http://cfaj.freeshell. org/google/> for details.

        --
        Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
        San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
        We must do something. This is something. Therefore, we must do this.

        Comment

        • Eric Sosman

          #5
          Re: Variable declaration and initialisation

          James Brodie wrote:
          [color=blue]
          > I just wanted to get some advice on what are the better practices:
          >
          > 1) Should variables be declared at the beginning of a function or just
          > before they are required?[/color]

          Under C89 rules, variable declarations in a block
          must precede all the executable statements at the same
          nesting level. A function body is a block, so all the
          "function-wide" variables must be declared at the top.
          Note, though, that nested blocks within the function's
          outermost block have their own scopes, and can contain
          their own variable declarations:

          void f(void) {
          int x;
          ...
          if (the_witch_is_d ead) {
          char message[] = "Ding, dong!";
          puts (message);
          ...
          }
          ...
          {
          double trouble;
          trouble = sqrt(toil);
          ...
          }
          }

          If you have a C99-conforming implementation, you can
          mix variable declarations and executable statements, the
          only requirement being that the declaration must precede
          all the uses.
          [color=blue]
          > 2) Should all variabled be initiailised immediately after declaration?[/color]

          No. Initialize those that need initialization, and
          leave the others alone. Under C99 rules, a case can be
          made for postponing the declaration until a point at which
          you know the first value that will be assigned to it, and
          declaring and initializing the variable at that point.
          Under C89 you might write

          void f(void) {
          int x;
          /* statements not involving x */
          x = g(z);
          /* statements using x */
          }

          .... and under C99 this might be a little better as

          void f(void) {
          /* statements not involving x */
          int x = g(z);
          /* statements involving x */
          }

          --
          Eric Sosman
          esosman@acm-dot-org.invalid

          Comment

          • Ian Collins

            #6
            Re: Variable declaration and initialisation

            Keith Thompson wrote:[color=blue]
            >
            > On the other hand, I see a lot of code that initializes a variable,
            > and then assigns a value to it before using it. A policy of *always*
            > initializing every variable, whether the initial value is used or not,
            > can avoid errors, but it's not always necessary.
            >[/color]
            It also prevents your compiler or lint from picking up unused variables.

            --
            Ian Collins.

            Comment

            • relient

              #7
              Re: Variable declaration and initialisation

              <quote>Keith Thompson:
              Even in C89/C90, you can declare variables at the beginning of any
              block, not just at the beginning of a function. For example:</quote>

              That's what I meant by "You must declare all your variables at the
              begining of the scope block." (notice I did not say function?) that
              includes the begining of a function and a block which has scope from {
              to } :P

              Comment

              • Keith Thompson

                #8
                Re: Variable declaration and initialisation

                "relient" <xllx.relient.x llx@gmail.com> writes:[color=blue]
                > <quote>Keith Thompson:
                > Even in C89/C90, you can declare variables at the beginning of any
                > block, not just at the beginning of a function. For example:</quote>
                >
                > That's what I meant by "You must declare all your variables at the
                > begining of the scope block." (notice I did not say function?) that
                > includes the begining of a function and a block which has scope from {
                > to } :P[/color]

                Right, I was amplifying, not disagreeing.

                BTW, the "<quote> ... "</quote>" syntax is better than nothing, but
                please use Usenet standard of prefixing each quoted line with "> ".
                See <http://cfaj.freeshell. org/google/> for details.

                --
                Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
                We must do something. This is something. Therefore, we must do this.

                Comment

                • Joe Wright

                  #9
                  Re: Variable declaration and initialisation

                  James Brodie wrote:[color=blue]
                  > I just wanted to get some advice on what are the better practices:
                  >
                  > 1) Should variables be declared at the beginning of a function or just
                  > before they are required?
                  >
                  > 2) Should all variabled be initiailised immediately after declaration?
                  >
                  > Thanks
                  >[/color]

                  It's taste and style. But first, you mean define, not declare. I still
                  write C89 and so I must define variables at the beginning of the block
                  before any function calls. C99 gives more lattitude as to where you can
                  place definitions.

                  I tend to initialize variables only as needed. For example..

                  int length(char *s) {
                  int i;
                  for (i = 0; s[i]; ++i) ;
                  ret i;
                  }

                  ...I don't initialize i on definition because the for statement does it.

                  --
                  Joe Wright
                  "Everything should be made as simple as possible, but not simpler."
                  --- Albert Einstein ---

                  Comment

                  • raju

                    #10
                    Re: Variable declaration and initialisation

                    hi i am new to c
                    will you please tell me the wat is c89 and c99 series and how
                    they are different

                    Comment

                    • Eric Sosman

                      #11
                      Re: Variable declaration and initialisation

                      raju wrote:[color=blue]
                      > hi i am new to c
                      > will you please tell me the wat is c89 and c99 series and how
                      > they are different[/color]

                      See Question 11.1 in the comp.lang.c Frequently Asked
                      Questions (FAQ) list



                      --
                      Eric Sosman
                      esosman@acm-dot-org.invalid

                      Comment

                      • Netocrat

                        #12
                        Re: Variable declaration and initialisation

                        On Mon, 16 Jan 2006 09:15:09 -0500, Eric Sosman wrote:[color=blue]
                        > raju wrote:[color=green]
                        >> hi i am new to c
                        >> will you please tell me the wat is c89 and c99 series and how
                        >> they are different[/color]
                        >
                        > See Question 11.1 in the comp.lang.c Frequently Asked
                        > Questions (FAQ) list
                        >
                        > http://c-faq.com/[/color]

                        And an adjunct:
                        <http://clc-wiki.net/wiki/Basics_Of_The_C _Standard>

                        --


                        Comment

                        • Richard Heathfield

                          #13
                          Re: Variable declaration and initialisation

                          Netocrat said:
                          [color=blue]
                          > <http://clc-wiki.net/wiki/Basics_Of_The_C _Standard>[/color]

                          You might want to get someone to look over that in a bit more detail. I
                          spotted one error, which I've corrected (Kernighan was certainly a
                          co-author of "The C Programming Language", but could hardly be described as
                          a creator of the C programming language), but there could be more. (Jack
                          Klein is probably the guy to ask about ratification dates etc, since he
                          seems to delight in correcting people who get them wrong!)

                          --
                          Richard Heathfield
                          "Usenet is a strange place" - dmr 29/7/1999

                          email: rjh at above domain (but drop the www, obviously)

                          Comment

                          • Netocrat

                            #14
                            Re: Variable declaration and initialisation

                            On Mon, 16 Jan 2006 15:25:28 +0000, Richard Heathfield wrote:[color=blue]
                            > Netocrat said:
                            >[color=green]
                            >> <http://clc-wiki.net/wiki/Basics_Of_The_C _Standard>[/color]
                            >
                            > You might want to get someone to look over that in a bit more detail. I
                            > spotted one error, which I've corrected (Kernighan was certainly a
                            > co-author of "The C Programming Language", but could hardly be described as
                            > a creator of the C programming language),[/color]

                            Right, from what I understand Ken Thompson would better fit that title.
                            Was "K&R" as an unofficial standard defined by more than just the white
                            book though? - I understand that AT&T manuals as well as Steven C.
                            Johnson's reference C implementation contributed to the language's
                            definition.
                            [color=blue]
                            > but there could be more.
                            > (Jack Klein is probably the guy to ask about ratification dates etc,
                            > since he seems to delight in correcting people who get them wrong!)[/color]

                            Any corrections that he has for that page are welcome - it should be as
                            accurate as possible.

                            --

                            Comment

                            • Richard Heathfield

                              #15
                              Re: Variable declaration and initialisation

                              Netocrat said:
                              [color=blue]
                              > On Mon, 16 Jan 2006 15:25:28 +0000, Richard Heathfield wrote:[color=green]
                              >> Netocrat said:
                              >>[color=darkred]
                              >>> <http://clc-wiki.net/wiki/Basics_Of_The_C _Standard>[/color]
                              >>
                              >> You might want to get someone to look over that in a bit more detail. I
                              >> spotted one error, which I've corrected (Kernighan was certainly a
                              >> co-author of "The C Programming Language", but could hardly be described
                              >> as a creator of the C programming language),[/color]
                              >
                              > Right, from what I understand Ken Thompson would better fit that title.[/color]

                              Try "Dennis Ritchie". I suspect dmr had much more input into Unix than kt
                              had into C. http://cm.bell-labs.com/cm/cs/who/dmr/chist.html is well worth
                              a read (and you might want to cross-refer to it from your site).

                              [color=blue]
                              > Was "K&R" as an unofficial standard defined by more than just the white
                              > book though?[/color]

                              I've heard it told both ways. Ask an old fart. (I get my generic o.f. badge
                              in about a year from now, but my C-specific o.f. badge is going to be a few
                              more years a-coming.)

                              --
                              Richard Heathfield
                              "Usenet is a strange place" - dmr 29/7/1999

                              email: rjh at above domain (but drop the www, obviously)

                              Comment

                              Working...