Declaration of Variables: Location

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • noridotjabi@gmail.com

    Declaration of Variables: Location

    Whilest I was browesing a tutorial today I came across the infromation
    that in standard C variables must be decalred at the beginning of a
    block. Meaning:

    /*************** *************** *************** *******/
    /* ... usual includes and such */
    int var = 1;

    if(var = 1){
    printf("hello world\n");
    }

    int a = 10;
    int b = 30;

    printf("%d %d", a, b);
    /* end return etc. */
    /*************** *************** *************** *******/

    Would form some kind of error and would need to be replaced with:
    /*************** *************** *************** *******/
    /* ... usual includes and such */
    int var = 1;
    if(var = 1){
    printf("hello world\n");
    }

    {
    int a = 10;
    int b = 30;
    printf("%d %d", a, b);
    }
    /* end return etc. */
    /*************** *************** *************** *******/

    This is news to me as I have never heard or seen anything like this.
    Infact I have assumed (but have never confirmed) that C was even
    equiped with a "naked block" feature. Can anyone offer any insight as
    to what is going on here. Also please correct me if I have
    misinturpreted someting as I expect that I might have.
    Nori

  • Ian Collins

    #2
    Re: Declaration of Variables: Location

    noridotjabi@gma il.com wrote:[color=blue]
    > Whilest I was browesing a tutorial today I came across the infromation
    > that in standard C variables must be decalred at the beginning of a
    > block.[/color]

    True for pre C99 code, fixed in C99.

    --
    Ian Collins.

    Comment

    • milhous.30@gmail.com

      #3
      Re: Declaration of Variables: Location

      This is the old sytle c....now c can handle the declaration of a
      variable any where, as long as it is only referenced after that point.
      The standard is more strict than what most compilers accept(gcc
      included). If you want strict use

      gcc -pedantic ...

      Comment

      • Andrew Poelstra

        #4
        Re: Declaration of Variables: Location

        Ian Collins wrote:[color=blue]
        > noridotjabi@gma il.com wrote:[color=green]
        >> Whilest I was browesing a tutorial today I came across the infromation
        >> that in standard C variables must be decalred at the beginning of a
        >> block.[/color]
        >
        > True for pre C99 code, fixed in C99.
        >[/color]

        I'd like to point out that code is far easier to read if all the
        variable declarations are at the top of each block. It also allows you
        to easily see what is and isn't in scope, assuming you indent each layer
        to blocks.


        Of course, that is just a preference of mine.
        --
        Andrew Poelstra <http://www.wpsoftware. net/blog>

        Every prime number in a series as a joke
        Made all the patterns clear when I took that final toke
        -- Numbers (Sunken Complexity)

        Comment

        • Keith Thompson

          #5
          Re: Declaration of Variables: Location

          Andrew Poelstra <apoelstra@shaw .ca> writes:[color=blue]
          > Ian Collins wrote:[color=green]
          >> noridotjabi@gma il.com wrote:[color=darkred]
          >>> Whilest I was browesing a tutorial today I came across the infromation
          >>> that in standard C variables must be decalred at the beginning of a
          >>> block.[/color]
          >> True for pre C99 code, fixed in C99.[/color]
          >
          > I'd like to point out that code is far easier to read if all the
          > variable declarations are at the top of each block. It also allows you
          > to easily see what is and isn't in scope, assuming you indent each
          > layer to blocks.
          >
          >
          > Of course, that is just a preference of mine.[/color]

          On the other hand, it can be useful to mix declarations and statements
          when an initialization depends on some previous computation in the
          same block:

          {
          char *p = malloc(ENOUGH_B YTES);
          if (p == NULL) {
          exit(EXIT_FAILU RE);
          }
          strcpy(p, some_string);
          strcat(p, some_other_stri ng);
          size_t len = strlen(p);
          ...
          }

          You can usually achieve the same effect by using assignments rather
          than initializations , but it's handy to be able to initialize each
          variable as it's declared.

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

          • Martin Ambuhl

            #6
            Re: Declaration of Variables: Location

            noridotjabi@gma il.com wrote:[color=blue]
            > Whilest I was browesing a tutorial today I came across the infromation
            > that in standard C variables must be decalred at the beginning of a
            > block.[/color]

            This was true before C99, but has not been for sometime.
            On the other hand, it is good programming practice to declare variable
            at the beginning of the block. Should you feel a real need to declare
            variables elsewhere, new blocks can be created and external routine can
            be used.

            [example of use of a inner block snipped]
            [color=blue]
            > This is news to me as I have never heard or seen anything like this.
            > Infact I have assumed (but have never confirmed) that C was even
            > equiped with a "naked block" feature.[/color]

            "Naked block" is not a C term. I admit my inability to make sense of
            the above. Had the second sentence said something to the effect that
            you assumed that C did *not* have such a feature, I would have noted
            that the braces, curly brackets, or whatever you prefer to call "{" and
            "}" enclose a compound statement. Compound statements are just
            statement. They need no special mechanism like control-structures or
            function declarations immediately preceding them.
            [color=blue]
            > Can anyone offer any insight as
            > to what is going on here. Also please correct me if I have
            > misinturpreted someting as I expect that I might have.
            > Nori
            >[/color]

            Comment

            • Richard Bos

              #7
              Re: Declaration of Variables: Location

              Ian Collins <ian-news@hotmail.co m> wrote:
              [color=blue]
              > noridotjabi@gma il.com wrote:[color=green]
              > > Whilest I was browesing a tutorial today I came across the infromation
              > > that in standard C variables must be decalred at the beginning of a
              > > block.[/color]
              >
              > True for pre C99 code, fixed in C99.[/color]

              s/fixed/broken/.

              Richard

              Comment

              • Ian Collins

                #8
                Re: Declaration of Variables: Location

                Richard Bos wrote:[color=blue]
                > Ian Collins <ian-news@hotmail.co m> wrote:
                >
                >[color=green]
                >>noridotjabi@g mail.com wrote:
                >>[color=darkred]
                >>>Whilest I was browesing a tutorial today I came across the infromation
                >>>that in standard C variables must be decalred at the beginning of a
                >>>block.[/color]
                >>
                >>True for pre C99 code, fixed in C99.[/color]
                >
                >
                > s/fixed/broken/.
                >[/color]
                :u

                --
                Ian Collins.

                Comment

                • Ben Pfaff

                  #9
                  Re: Declaration of Variables: Location

                  rlb@hoekstra-uitgeverij.nl (Richard Bos) writes:
                  [color=blue]
                  > Ian Collins <ian-news@hotmail.co m> wrote:
                  >[color=green]
                  >> noridotjabi@gma il.com wrote:[color=darkred]
                  >> > Whilest I was browesing a tutorial today I came across the infromation
                  >> > that in standard C variables must be decalred at the beginning of a
                  >> > block.[/color]
                  >>
                  >> True for pre C99 code, fixed in C99.[/color]
                  >
                  > s/fixed/broken/.[/color]

                  You're the second person who's indicated a strong bias in favor
                  of declaring all variables at the beginning of the block. Can
                  you explain further? I like the idea of being able to initialize
                  my variables at the point of declaration whenever possible, so I
                  like the idea of mid-block declarations. (However, I don't
                  really get to use them because I also like my code to be
                  C89-friendly.)
                  --
                  "I'm not here to convince idiots not to be stupid.
                  They won't listen anyway."
                  --Dann Corbit

                  Comment

                  • Vladimir Oka

                    #10
                    Re: Declaration of Variables: Location


                    Ben Pfaff wrote:[color=blue]
                    > rlb@hoekstra-uitgeverij.nl (Richard Bos) writes:
                    >[color=green]
                    > > Ian Collins <ian-news@hotmail.co m> wrote:
                    > >[color=darkred]
                    > >> noridotjabi@gma il.com wrote:
                    > >> > Whilest I was browesing a tutorial today I came across the infromation
                    > >> > that in standard C variables must be decalred at the beginning of a
                    > >> > block.
                    > >>
                    > >> True for pre C99 code, fixed in C99.[/color]
                    > >
                    > > s/fixed/broken/.[/color]
                    >
                    > You're the second person who's indicated a strong bias in favor
                    > of declaring all variables at the beginning of the block.[/color]

                    I'd be the third then...
                    [color=blue]
                    > Can you explain further?[/color]

                    I can see the benefit (or "benefit") from declaring a variable close to
                    the place of first use when writing code. However, when reading code, I
                    find it much easier to have a single, well deifned place to look up all
                    the variables declared in a block. You can even have that bit open in a
                    separate window for quick reference.
                    [color=blue]
                    > I like the idea of being able to initialize my variables at the point of
                    > declaration whenever possible, so I like the idea of mid-block declarations.[/color]

                    You can still initialise the variables just before using them.
                    [color=blue]
                    > (However, I don't really get to use them because I also like my code to be
                    > C89-friendly.)[/color]

                    Another good reason.

                    Comment

                    • John Bode

                      #11
                      Re: Declaration of Variables: Location


                      noridotjabi@gma il.com wrote:[color=blue]
                      > Whilest I was browesing a tutorial today I came across the infromation
                      > that in standard C variables must be decalred at the beginning of a
                      > block.[/color]

                      [snip example]
                      [color=blue]
                      >
                      > This is news to me as I have never heard or seen anything like this.
                      > Infact I have assumed (but have never confirmed) that C was even
                      > equiped with a "naked block" feature. Can anyone offer any insight as
                      > to what is going on here. Also please correct me if I have
                      > misinturpreted someting as I expect that I might have.
                      > Nori[/color]

                      For pre-C99 implementations , all block-scope variables must be declared
                      at the beginning of the block. For C99 implementations , block-scope
                      variables can be declared anywhere within a block (with the obvious
                      restriction that they must be declared before they're used).

                      I have no idea what you mean by a "naked" block. As of C99, there are
                      implicit blocks associated with iterative and conditional statements;
                      I'm not sure if this is what you're thinking about.

                      Like everything else in programming, it's all about tradeoffs. The
                      good thing about having all your variables declared at the head of the
                      block is that it (arguably) improves readability (if you're wondering
                      about whether x is int or long, you immediately know where to look).
                      The good thing about declaring your variables as needed throughout the
                      code is that it limits the scope of those variables to where they're
                      actually used, and reduces the chance that a variable accidentally gets
                      used in multiple contexts (not a common mistake IME, but it does
                      happen; it's usually a sign that the code needs restructuring).

                      Comment

                      • CBFalconer

                        #12
                        Re: Declaration of Variables: Location

                        Vladimir Oka wrote:[color=blue]
                        > Ben Pfaff wrote:[color=green]
                        >> rlb@hoekstra-uitgeverij.nl (Richard Bos) writes:[color=darkred]
                        >>> Ian Collins <ian-news@hotmail.co m> wrote:
                        >>>> noridotjabi@gma il.com wrote:[/color][/color]
                        >[color=green][color=darkred]
                        >>>>> Whilest I was browesing a tutorial today I came across the
                        >>>>> infromation that in standard C variables must be decalred at
                        >>>>> the beginning of a block.
                        >>>>
                        >>>> True for pre C99 code, fixed in C99.
                        >>>
                        >>> s/fixed/broken/.[/color]
                        >>
                        >> You're the second person who's indicated a strong bias in favor
                        >> of declaring all variables at the beginning of the block.[/color]
                        >
                        > I'd be the third then...
                        >[color=green]
                        >> Can you explain further?[/color]
                        >
                        > I can see the benefit (or "benefit") from declaring a variable
                        > close to the place of first use when writing code. However, when
                        > reading code, I find it much easier to have a single, well deifned
                        > place to look up all the variables declared in a block. You can
                        > even have that bit open in a separate window for quick reference.
                        >[color=green]
                        >> I like the idea of being able to initialize my variables at the
                        >> point of declaration whenever possible, so I like the idea of
                        >> mid-block declarations.[/color]
                        >
                        > You can still initialise the variables just before using them.
                        >[color=green]
                        >> (However, I don't really get to use them because I also like my
                        >> code to be C89-friendly.)[/color]
                        >
                        > Another good reason.[/color]

                        For once I can only agree. A further factor is that I was brought
                        up on more disciplined languages, such as Pascal.

                        On the initialization point, initialization of local variables
                        generates code. It just isn't as obvious. In Pascal there are no
                        initialization statements, so one gets in the habit of writing the
                        appropriate code in the appropriate places.

                        --
                        "If you want to post a followup via groups.google.c om, don't use
                        the broken "Reply" link at the bottom of the article. Click on
                        "show options" at the top of the article, then click on the
                        "Reply" at the bottom of the article headers." - Keith Thompson
                        More details at: <http://cfaj.freeshell. org/google/>
                        Also see <http://www.safalra.com/special/googlegroupsrep ly/>


                        Comment

                        • Jack Klein

                          #13
                          Re: Declaration of Variables: Location

                          On Thu, 27 Apr 2006 04:40:08 GMT, Martin Ambuhl
                          <mambuhl@earthl ink.net> wrote in comp.lang.c:
                          [color=blue]
                          > noridotjabi@gma il.com wrote:[color=green]
                          > > Whilest I was browesing a tutorial today I came across the infromation
                          > > that in standard C variables must be decalred at the beginning of a
                          > > block.[/color]
                          >
                          > This was true before C99, but has not been for sometime.
                          > On the other hand, it is good programming practice to declare variable
                          > at the beginning of the block. Should you feel a real need to declare
                          > variables elsewhere, new blocks can be created and external routine can
                          > be used.
                          >
                          > [example of use of a inner block snipped]
                          >[color=green]
                          > > This is news to me as I have never heard or seen anything like this.
                          > > Infact I have assumed (but have never confirmed) that C was even
                          > > equiped with a "naked block" feature.[/color]
                          >
                          > "Naked block" is not a C term. I admit my inability to make sense of
                          > the above. Had the second sentence said something to the effect that
                          > you assumed that C did *not* have such a feature, I would have noted
                          > that the braces, curly brackets, or whatever you prefer to call "{" and
                          > "}" enclose a compound statement. Compound statements are just
                          > statement. They need no special mechanism like control-structures or
                          > function declarations immediately preceding them.[/color]

                          I took the OP's use of the term "naked block" to be the technique I
                          sometimes use when maintaining or updating code, my own and others.

                          I took it to mean a block (obviously enclosed by { and }) that was
                          free standing, not following a if/while/do/switch statement.

                          Consider having to make a change to a value in a function written by
                          somebody else:

                          int the_func(int x, int y, int z)
                          {
                          int local;
                          /* other declarations */

                          /* ... */

                          local = some_calculatio n();

                          /* ... */

                          return local;
                          }

                          I have to allow for a new feature in the code. Under some
                          circumstances which might be complex to evaluate, the function has to
                          return a value completely related to that returned by
                          some_calculatio n(). Under other circumstances, is returns the
                          original result.

                          Now one thing I could do is put the "local =" statement inside an if()
                          with the other possibility in the else clause. But in a complex
                          original function, and if the test and new calculation are complex as
                          well, this causes enough editing to create a non-trivial chance of
                          introducing defects.

                          So I introduce a "naked block", to make sure that I don't trample on
                          anything in an outer scope:

                          int the_func(int x, int y, int z)
                          {
                          int local;
                          /* other declarations */

                          /* ... */

                          local = some_calculatio n();

                          {
                          int tst1 = some_test();
                          int tst2 = another_test();
                          int tst3 = yet_another_tes t();

                          if ((tst1 == 42) && (tst1 < tst2) && (tst3 > (tst2 - tst1)))
                          {
                          int inner = /* ... */
                          /* perhaps call several functions to get values, */
                          /* perform calculations and so on to get new return value */
                          local = inner;
                          }
                          }

                          /* ... */

                          return local;
                          }

                          By introducing the naked block, I create a new scope and only modify
                          one value outside that scope, namely to change the return value when
                          the appropriate conditions exist. The only way my addition can change
                          the behavior of the code, other than what I intended, is through side
                          effects of any functions called inside the block. I can't
                          accidentally change the value of any object that the_func() might use
                          after my block, because I modify only values defined within the block.

                          I could do the same by defining new objects at the top of the_func(),
                          but then I run the risk accidentally hiding a name at wider scope.

                          --
                          Jack Klein
                          Home: http://JK-Technology.Com
                          FAQs for
                          comp.lang.c http://c-faq.com/
                          comp.lang.c++ http://www.parashift.com/c++-faq-lite/
                          alt.comp.lang.l earn.c-c++

                          Comment

                          • Richard Bos

                            #14
                            Re: Declaration of Variables: Location

                            Ben Pfaff <blp@cs.stanfor d.edu> wrote:
                            [color=blue]
                            > rlb@hoekstra-uitgeverij.nl (Richard Bos) writes:
                            >[color=green]
                            > > Ian Collins <ian-news@hotmail.co m> wrote:
                            > >[color=darkred]
                            > >> noridotjabi@gma il.com wrote:
                            > >> > Whilest I was browesing a tutorial today I came across the infromation
                            > >> > that in standard C variables must be decalred at the beginning of a
                            > >> > block.
                            > >>
                            > >> True for pre C99 code, fixed in C99.[/color]
                            > >
                            > > s/fixed/broken/.[/color]
                            >
                            > You're the second person who's indicated a strong bias in favor
                            > of declaring all variables at the beginning of the block. Can
                            > you explain further? I like the idea of being able to initialize
                            > my variables at the point of declaration whenever possible, so I
                            > like the idea of mid-block declarations.[/color]

                            I've seen too much (C-plus-extensions, pre-C99) code where declarations
                            were thrown into the code at any which point, without intervening
                            whitespace, and generally made less conspicuous with a nice, complex
                            initialiser which makes it look more like an ordinary assignment.
                            While I don't disagree that it _can_ be used correctly, the temptation
                            to make declarations impossible to find at a glance is apparently too
                            great for too many programmers.
                            If you really _need_ a mid-code declaration, you can always open another
                            block. That has the added advantage of making it stand out.

                            Richard

                            Comment

                            • websnarf@gmail.com

                              #15
                              Re: Declaration of Variables: Location

                              Andrew Poelstra wrote:[color=blue]
                              > Ian Collins wrote:[color=green]
                              > > noridotjabi@gma il.com wrote:[color=darkred]
                              > >> Whilest I was browesing a tutorial today I came across the infromation
                              > >> that in standard C variables must be decalred at the beginning of a
                              > >> block.[/color]
                              > >
                              > > True for pre C99 code, fixed in C99.[/color]
                              >
                              > I'd like to point out that code is far easier to read if all the
                              > variable declarations are at the top of each block. It also allows you
                              > to easily see what is and isn't in scope, assuming you indent each layer
                              > to blocks.[/color]

                              Yeah, and it also clearly deliniates between code and declarations. So
                              I would say it got "broken" in C99.

                              C++ added this because they wanted greater control over construction
                              (though they ignored the corresponding issue for destruction, for some
                              reason). The C language does not have such an issue, or even one
                              analogous to it.
                              [color=blue]
                              > Of course, that is just a preference of mine.[/color]

                              I'm with you.

                              --
                              Paul Hsieh
                              Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.



                              Comment

                              Working...