Variable declaration and initialisation

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

    #16
    Re: Variable declaration and initialisation

    On Mon, 16 Jan 2006 17:25:53 +0000, Richard Heathfield wrote:[color=blue]
    > Netocrat said:[color=green]
    >> On Mon, 16 Jan 2006 15:25:28 +0000, Richard Heathfield wrote:[color=darkred]
    >>> Netocrat said:
    >>>
    >>>> <http://clc-wiki.net/wiki/Basics_Of_The_C _Standard>
    >>>
    >>> 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".[/color]

    Oh, that goes without saying. I meant that Ken Thompson would better fit
    the title of co-creator of C than Brian Kernighan, but rereading what I
    wrote I see that it wasn't particularly clear, and as you write below, his
    role may not have been as significant as to warrant that title (not having
    been there at the time, I won't judge).
    [color=blue]
    > 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]

    Or you or any other c.l.c.er - it's intended as a group wiki, not a
    personal site. But point taken, I'm aware of that article and it deserves
    to be linked to from somewhere in the wiki - probably an "external links"
    or "historical notes" page.
    [color=blue][color=green]
    >> 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.[/color]

    I've just found where I first read this. Douglas Gwyn on 2 Nov 2005 in
    comp.std.c wrote:
    [color=blue]
    > K&R(1) Appendix A was one of the main guides to C before there was an
    > official standard, but actual implementations of C did not accurately
    > follow the spec in that Appendix, and there were several generally
    > accepted changes to the language and library beyond what K&R described.
    > The AT&T C Reference Manual was considered by many to be more
    > authoritative.[/color]

    <http://groups.google.c om/group/comp.std.c/msg/0933afffda92e8f 6>

    It's not clear from this though whether the "generally accepted changes"
    and/or those in the AT&T manual would form part of what we now, looking
    back, refer to as "K&R C". I've come across descriptions that seem to
    suggest one or more of "DMR's compiler for the pdp-11", "Johnson's PCC"
    and "AT&T's compiler" could be thought of as reference implementations .

    --

    Comment

    • Richard Heathfield

      #17
      Re: Variable declaration and initialisation

      Netocrat said:
      [color=blue][color=green][color=darkred]
      >>> 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.[/color]
      >
      > I've just found where I first read this. Douglas Gwyn on 2 Nov 2005 in
      > comp.std.c wrote:[/color]

      Well, if Doug said it, it's probably so. He certainly counts as an old fart,
      if he'll forgive me for saying so; he is, after all, mentioned in
      dispatches in K&R's acks section.

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

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

      Comment

      • Emmanuel Delahaye

        #18
        Re: Variable declaration and initialisation

        James Brodie a écrit :[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]

        Yes, at the top of a block. The block bounds the scope of the object.
        IMO, it's a Good Thing for objects and functions to have a reduced to
        minimum scope.

        It helps reading, maintenance and preapre the code for modularization.
        It also forces the coder (and the compiler) to check the initialisation
        and prevents against the uncontrolled reuse of an object (with a wrong
        init value).
        [color=blue]
        > 2) Should all variabled be initiailised immediately after declaration?[/color]

        In most cases, yes, specially pointers. (NULL or their nominal value).

        Special case:

        int i;

        for (i = 0; i < 10; i++)

        is, IMO, better than a religious :

        int i = 0;

        for (; i < 10; i++)

        but it's prpbably more a style issue...

        --
        A+

        Emmanuel Delahaye

        Comment

        • Eric Sosman

          #19
          Re: Variable declaration and initialisation

          Emmanuel Delahaye wrote:[color=blue]
          > James Brodie a écrit :
          >[color=green]
          >> 2) Should all variabled be initiailised immediately after declaration?[/color]
          >
          > In most cases, yes, specially pointers. (NULL or their nominal value).[/color]

          In most cases, no. Here's an example of why not:

          void f(void) {
          char *p;
          char *q;
          p = malloc(strlen(s tring1) + 1);
          if (p == NULL)
          die();
          strcpy (p, string1);
          p = malloc(strlen(s tring2) + 1);
          if (q == NULL)
          die();
          strcpy (q, string2);
          ...

          Some compilers are able to detect and warn about the use
          of uninitialized variables, and such compilers will catch
          the error in the above code. If the two variables were
          initialized to NULL (or whatever) at declaration, the
          error would go unnoticed until run-time. The effect of
          the initialization, then, is simply to defeat the compiler's
          attempt to be helpful and to slow down the detection of
          the error.

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

          Comment

          • Emmanuel Delahaye

            #20
            Re: Variable declaration and initialisation

            Eric Sosman a écrit :[color=blue]
            > In most cases, no. Here's an example of why not:
            >
            > void f(void) {
            > char *p;
            > char *q;
            > p = malloc(strlen(s tring1) + 1);
            > if (p == NULL)
            > die();
            > strcpy (p, string1);
            > p = malloc(strlen(s tring2) + 1);
            > if (q == NULL)
            > die();
            > strcpy (q, string2);
            > ...
            >
            > Some compilers are able to detect and warn about the use
            > of uninitialized variables, and such compilers will catch
            > the error in the above code. If the two variables were
            > initialized to NULL (or whatever) at declaration, the
            > error would go unnoticed until run-time. The effect of
            > the initialization, then, is simply to defeat the compiler's
            > attempt to be helpful and to slow down the detection of
            > the error.[/color]
            I understand your point, but I prefer to use a different coding
            technique based on the reduction of the scope of functions and objects:

            void f(void)
            {
            {
            char *p = malloc(strlen(s tring1) + 1);
            if (p == NULL)
            die();
            strcpy (p, string1);
            }

            {
            char *q = malloc(strlen(s tring2) + 1);

            if (q == NULL)
            die();
            strcpy (q, string2);
            }
            <...>

            and magically, the bug did'nt happen at all.

            --
            A+

            Emmanuel Delahaye

            Comment

            • Eric Sosman

              #21
              Re: Variable declaration and initialisation



              Emmanuel Delahaye wrote On 01/17/06 16:09,:[color=blue]
              > Eric Sosman a écrit :
              > [color=green]
              >> In most cases, no. Here's an example of why not:
              >>
              >> void f(void) {
              >> char *p;
              >> char *q;
              >> p = malloc(strlen(s tring1) + 1);
              >> if (p == NULL)
              >> die();
              >> strcpy (p, string1);
              >> p = malloc(strlen(s tring2) + 1);
              >> if (q == NULL)
              >> die();
              >> strcpy (q, string2);
              >> ...
              >>
              >>Some compilers are able to detect and warn about the use
              >>of uninitialized variables, and such compilers will catch
              >>the error in the above code. If the two variables were
              >>initialized to NULL (or whatever) at declaration, the
              >>error would go unnoticed until run-time. The effect of
              >>the initialization, then, is simply to defeat the compiler's
              >>attempt to be helpful and to slow down the detection of
              >>the error.[/color]
              >
              > I understand your point, but I prefer to use a different coding
              > technique based on the reduction of the scope of functions and objects:
              >
              > void f(void)
              > {
              > {
              > char *p = malloc(strlen(s tring1) + 1);
              > if (p == NULL)
              > die();
              > strcpy (p, string1);
              > }
              >
              > {
              > char *q = malloc(strlen(s tring2) + 1);
              >
              > if (q == NULL)
              > die();
              > strcpy (q, string2);
              > }
              > <...>
              >
              > and magically, the bug did'nt happen at all.[/color]

              And if you need to work with both p and q in the
              same scope ...?

              For example, if die() is "return an indication of
              failure, e.g., -1 or NULL" (and the return type of f()
              is suitably adjusted), the die() after the failure to
              allocate memory for q would presumably want to free(p)
              so as not to leak memory. What then?

              We could go on making up examples and counter-examples
              pretty much indefinitely, especially since neither point
              of view is entirely unreasonable. (Mine is MORE reasonable
              than yours, OF COURSE, harrumph, harrumph, but that's
              another matter. ;-) However, the O.P.'s question was
              [color=blue]
              > 2) Should all variabled be initiailised immediately
              > after declaration?[/color]

              ... and I think you'll agree that the word "all" calls
              for the answer "No" from both the Usually-Initialize and
              the Usually-Don't crowd.

              (Strangest language I ever saw had an interesting way
              of catching attempts to use uninitialized variables. They
              were always accessed via indirection through a sort of
              symbol table, and the compiler deliberately set the low-
              order bits of the table's pointers so they'd be mis-aligned.
              On a write, the code zeroed the pointer's low-order bit,
              but on a read it simply used what the table contained.
              Result: Try to read a variable before a write has repaired
              its pointer, and you get a hardware trap. The run-time
              would print a diagnostic message giving the name of the
              variable and the line that performed the bad reference, and
              then would initialize the variable to 1 and resume. Why 1?
              Just in case the program was about to divide by it ...)

              --
              Eric.Sosman@sun .com

              Comment

              • Mark B

                #22
                Re: Variable declaration and initialisation


                "Emmanuel Delahaye" <emdel@YOURBRAn oos.fr> wrote in message
                news:43cd5d05$0 $3954$79c14f64@ nan-newsreader-06.noos.net...[color=blue]
                > Eric Sosman a écrit :[color=green]
                >> In most cases, no. Here's an example of why not:
                >>
                >> void f(void) {
                >> char *p;
                >> char *q;
                >> p = malloc(strlen(s tring1) + 1);
                >> if (p == NULL)
                >> die();
                >> strcpy (p, string1);
                >> p = malloc(strlen(s tring2) + 1);
                >> if (q == NULL)
                >> die();
                >> strcpy (q, string2);
                >> ...
                >>
                >> Some compilers are able to detect and warn about the use
                >> of uninitialized variables, and such compilers will catch
                >> the error in the above code. If the two variables were
                >> initialized to NULL (or whatever) at declaration, the
                >> error would go unnoticed until run-time. The effect of
                >> the initialization, then, is simply to defeat the compiler's
                >> attempt to be helpful and to slow down the detection of
                >> the error.[/color]
                > I understand your point, but I prefer to use a different coding technique
                > based on the reduction of the scope of functions and objects:
                >
                > void f(void)
                > {
                > {
                > char *p = malloc(strlen(s tring1) + 1);
                > if (p == NULL)
                > die();
                > strcpy (p, string1);
                > }
                >
                > {
                > char *q = malloc(strlen(s tring2) + 1);
                >
                > if (q == NULL)
                > die();
                > strcpy (q, string2);
                > }
                > <...>
                >
                > and magically, the bug did'nt happen at all.[/color]

                Your code is most definately not the equivalent of Eric's.
                His is meant to perform further work with the dynamically
                allocated memory segments and I'm sure they'll later be
                freed in the section left out (specified by the elipses).
                Yours created 2 memory leaks! :-)


                Comment

                • Emmanuel Delahaye

                  #23
                  Re: Variable declaration and initialisation

                  Mark B a écrit :[color=blue]
                  > Your code is most definately not the equivalent of Eric's.
                  > His is meant to perform further work with the dynamically
                  > allocated memory segments and I'm sure they'll later be
                  > freed in the section left out (specified by the elipses).
                  > Yours created 2 memory leaks! :-)[/color]

                  Ahem... say "the ellipses was misplaced", huh...

                  --
                  A+

                  Emmanuel Delahaye

                  Comment

                  Working...