static and initialization rules or 0 is 0.0 is NULL

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

    static and initialization rules or 0 is 0.0 is NULL

    I don't know what to think of the following..
    (from the dietlibc FAQ)
    Q: I see lots of uninitialized variables, like "static int foo;". What
    gives?
    A: "static" global variables are initialized to 0. ANSI C guarantees that.
    Technically speaking, static variables go into the .bss ELF segment,
    while "static int foo=0" goes into .data. Because .bss is zero
    filled by the OS, it does not need to be in the actual binary. So it
    is in fact better to not initialize static variables if the desired
    initialization value is 0 anyway. The same is true for pointers, by
    the way. On all platforms supported by the diet libc, numeric zero
    is also the pointer value for NULL. So not initializing a static
    pointer yields NULL.

    So far I am still initializing all my variables by hand. I could save a lot
    of code if I removed all the to zero/NULL initializations for static
    globals..
    I am kind of worried about subtile breakage, though. Does a platform where 0
    != NULL is true actually exist? Does the ANSI standard even allow such
    platforms?
    And how far does this "intialized to 0" guarantee go? Are floating point
    values guaranteed to be 0.0? Are all bytes of char array 0x00? What about
    structures?

    I have never been bold enough to just do memset(structur e, 0,
    sizeof(structur e)) if I wanted all members of the structure to be some kind
    of zero (NULL pointer, 0 float, 0 byte, 0 int).

    What should one do?





  • Barry Schwarz

    #2
    Re: static and initialization rules or 0 is 0.0 is NULL

    On Mon, 2 Jun 2008 00:58:50 +0200, "copx" <copx@gazeta.pl wrote:
    >I don't know what to think of the following..
    >(from the dietlibc FAQ)
    >Q: I see lots of uninitialized variables, like "static int foo;". What
    >gives?
    >A: "static" global variables are initialized to 0. ANSI C guarantees that.
    The first sentence is guaranteed by the standard.
    Technically speaking, static variables go into the .bss ELF segment,
    The rest is specific to this particular system and irrelevant to your
    question.
    while "static int foo=0" goes into .data. Because .bss is zero
    filled by the OS, it does not need to be in the actual binary. So it
    is in fact better to not initialize static variables if the desired
    initialization value is 0 anyway. The same is true for pointers, by
    the way. On all platforms supported by the diet libc, numeric zero
    is also the pointer value for NULL. So not initializing a static
    pointer yields NULL.
    >
    >So far I am still initializing all my variables by hand. I could save a lot
    >of code if I removed all the to zero/NULL initializations for static
    >globals..
    While you may save a lot of typing, it is unlikely that it will save
    any code execution except on a system which (perversely) makes it a
    point to treat the default initialization different than
    initialization to the default value.
    >I am kind of worried about subtile breakage, though. Does a platform where 0
    >!= NULL is true actually exist? Does the ANSI standard even allow such
    >platforms?
    You are confusing the value 0 with setting an object to all bits zero.
    While this works for the various integer types, it is not guaranteed
    to work for other types.

    When the int literal 0 is assigned to an object pointer, that pointer
    will be assigned the NULL value for that type of pointer. In other
    words
    ptr = NULL;
    and
    ptr = 0;
    are guaranteed to have the same effect. A similar guarantee is
    provided for comparison (ptr == NULL and ptr == 0 and !=). It goes so
    far as to include conditional statements like if and while and the
    ternary operator ?: (if (ptr) will evaluate the same as if (ptr !=
    0)).

    None of this tells you anything about the bit representation of a
    pointer which has been assigned the NULL value. Yes, the standard
    does allow a NULL pointer to have a representation other than all bits
    zero. However, in this case the compiler must generate the correct
    code so that ptr = 0; still results in the correct NULL value being
    assigned to the pointer.

    By the way, the same is true for floating point. 0.0 need not be
    represented by all bits 0.
    >And how far does this "intialized to 0" guarantee go? Are floating point
    All the way.
    >values guaranteed to be 0.0? Are all bytes of char array 0x00? What about
    >structures?
    Yes. Only when CHAR_BIT is 8 (otherwise you need more zeros after the
    x). A structure (and any other aggregate) are initialized with the
    same rules applied recursively to the members of the structure
    (elements of the aggregate).
    >
    >I have never been bold enough to just do memset(structur e, 0,
    >sizeof(structu re)) if I wanted all members of the structure to be some kind
    >of zero (NULL pointer, 0 float, 0 byte, 0 int).
    While it will work on your system, it would not be portable.
    >
    >What should one do?
    >
    Let the compiler do the work for you.


    Remove del for email

    Comment

    • Bartc

      #3
      Re: static and initialization rules or 0 is 0.0 is NULL


      "copx" <copx@gazeta.pl wrote in message
      news:g1v9jg$p23 $1@inews.gazeta .pl...
      >I don't know what to think of the following..
      (from the dietlibc FAQ)
      Q: I see lots of uninitialized variables, like "static int foo;". What
      gives?
      A: "static" global variables are initialized to 0. ANSI C guarantees
      that.
      Technically speaking, static variables go into the .bss ELF segment,
      while "static int foo=0" goes into .data. Because .bss is zero
      filled by the OS, it does not need to be in the actual binary. So it
      is in fact better to not initialize static variables if the desired
      initialization value is 0 anyway. The same is true for pointers, by
      the way. On all platforms supported by the diet libc, numeric zero
      is also the pointer value for NULL. So not initializing a static
      pointer yields NULL.
      >
      So far I am still initializing all my variables by hand. I could save a
      lot of code if I removed all the to zero/NULL initializations for static
      globals..
      You might save some typing. I doubt it will make the program smaller.

      --
      Bartc


      Comment

      • Ben Bacarisse

        #4
        Re: static and initialization rules or 0 is 0.0 is NULL

        Barry Schwarz <schwarzb@dqel. comwrites:
        On Mon, 2 Jun 2008 00:58:50 +0200, "copx" <copx@gazeta.pl wrote:
        <snip your excellent explanations>
        >>values guaranteed to be 0.0? Are all bytes of char array 0x00? What about
        >>structures?
        >
        Yes. Only when CHAR_BIT is 8 (otherwise you need more zeros after the
        x).
        Surely 0x00 is just another way to write 0 and will zero initialise a
        char of any width.

        <snip>
        >>I have never been bold enough to just do memset(structur e, 0,
        >>sizeof(struct ure)) if I wanted all members of the structure to be some kind
        >>of zero (NULL pointer, 0 float, 0 byte, 0 int).
        >
        While it will work on your system, it would not be portable.
        >
        >>What should one do?
        To the OP: one portable alternative is to write a zeroing function
        like this:

        void zero_some_struc t(struct S *sp)
        {
        static struct S = {0};
        *sp = S;
        }

        not always a good idea, but worth considering.

        --
        Ben.

        Comment

        • copx

          #5
          Re: static and initialization rules or 0 is 0.0 is NULL


          "Bartc" <bc@freeuk.coms chrieb im Newsbeitrag
          news:6DH0k.1730 $E41.1587@text. news.virginmedi a.com...
          >
          "copx" <copx@gazeta.pl wrote in message
          news:g1v9jg$p23 $1@inews.gazeta .pl...
          >>I don't know what to think of the following..
          >(from the dietlibc FAQ)
          >Q: I see lots of uninitialized variables, like "static int foo;". What
          >gives?
          >A: "static" global variables are initialized to 0. ANSI C guarantees
          >that.
          > Technically speaking, static variables go into the .bss ELF segment,
          > while "static int foo=0" goes into .data. Because .bss is zero
          > filled by the OS, it does not need to be in the actual binary. So it
          > is in fact better to not initialize static variables if the desired
          > initialization value is 0 anyway. The same is true for pointers, by
          > the way. On all platforms supported by the diet libc, numeric zero
          > is also the pointer value for NULL. So not initializing a static
          > pointer yields NULL.
          >>
          >So far I am still initializing all my variables by hand. I could save a
          >lot of code if I removed all the to zero/NULL initializations for static
          >globals..
          >
          You might save some typing. I doubt it will make the program smaller.
          It does. Example:

          static int foo;

          void lib_init(void)
          {
          foo = 0;
          }

          Compile and check the assembly. The compiler has to put the code to set foo
          to 0 into lib_init() because it cannot know when lib_init() might be called.
          It is perfectly possible that lib_init() will be called after the value of
          foo has been changed by some other function.
          In theory a compiler could remove such code in some cases if it does whole
          program optimization and hyper-advanced program flow analyses to figure out
          that lib_init() will indeed only be called once and at a time when foo is
          still guaranteed to be zero.
          However, even if such a god-like compiler existed, the optimization routine
          wouldn't work in cases where the program flow is not predictable at compile
          time (it often isn't).


          Comment

          • Thad Smith

            #6
            Re: static and initialization rules or 0 is 0.0 is NULL

            Bartc wrote:
            "copx" <copx@gazeta.pl wrote in message
            news:g1v9jg$p23 $1@inews.gazeta .pl...
            >So far I am still initializing all my variables by hand. I could save a
            >lot of code if I removed all the to zero/NULL initializations for static
            >globals..
            >
            You might save some typing. I doubt it will make the program smaller.
            If the OP is assigning zero instead of using an initializer, the code will
            be shorter. If he is using an explicit initializer with value zero, some
            implementations will probably include an entry in an initialization table
            of the program image for the loader making it larger, whereas implicit
            initialization to zero would not. The Standard, of course, doesn't address
            this implementation issue.

            --
            Thad

            Comment

            • copx

              #7
              Re: static and initialization rules or 0 is 0.0 is NULL


              "Ben Bacarisse" <ben.usenet@bsb .me.ukschrieb im Newsbeitrag
              news:87mym4lk2l .fsf@bsb.me.uk. ..
              [snip]
              >>>What should one do?
              >
              To the OP: one portable alternative is to write a zeroing function
              like this:
              >
              void zero_some_struc t(struct S *sp)
              {
              static struct S = {0};
              *sp = S;
              }
              >
              not always a good idea, but worth considering.
              This was not portable the last time I checked. I once tried to compile some
              C code that was full of the assumption that "structure = {0}" zeros all
              members of the the structure. That works in GCC's "GNU C" mode (or at least
              it used to work) but lcc-win32 rejected the code (at that time). In the high
              warning level/ANSI mode I use when compiling with GCC your code would
              produce a "missing initializer" warning if struct S contains more than one
              member.



              Comment

              • copx

                #8
                Re: static and initialization rules or 0 is 0.0 is NULL


                "copx" <copx@gazeta.pl schrieb im Newsbeitrag
                news:g1v9jg$p23 $1@inews.gazeta .pl...
                >I don't know what to think of the following..
                [snip]

                @Barry Schwarz

                Thank you for the detailed explanation. I could not directly reply to your
                post because it did not show up on my news server.



                Comment

                • Keith Thompson

                  #9
                  Re: static and initialization rules or 0 is 0.0 is NULL

                  "copx" <copx@gazeta.pl writes:
                  I don't know what to think of the following..
                  (from the dietlibc FAQ)
                  Q: I see lots of uninitialized variables, like "static int foo;". What
                  gives?
                  A: "static" global variables are initialized to 0. ANSI C guarantees that.
                  Technically speaking, static variables go into the .bss ELF segment,
                  while "static int foo=0" goes into .data. Because .bss is zero
                  filled by the OS, it does not need to be in the actual binary. So it
                  is in fact better to not initialize static variables if the desired
                  initialization value is 0 anyway. The same is true for pointers, by
                  the way. On all platforms supported by the diet libc, numeric zero
                  is also the pointer value for NULL. So not initializing a static
                  pointer yields NULL.
                  A static pointer with no initialization is initialized to NULL (more
                  precisely, to a null pointer value). This is true, not because a null
                  pointer is probably represented as all-bits-zero, but because the
                  standard guarantees it, regardless of the representation of a null
                  pointer.

                  Any declared object is of either a scalar type (integer, floating, or
                  pointer) or an aggregate type (array, struct, or union). Aggregates
                  in turn are made up of sub-ojects, which themselves can be scalars or
                  aggregates. If you dig down far enough, any object is nothing but a
                  collection of one or more scalars.

                  A scalar that is, or is part of, a static object with no initalization
                  is implicitly initialized to 0, converted to the appropriate type.
                  Converting 0 to an integer type yields 0 of that type (could be 0L
                  (long int), 0UL (unsigned long int), etc.). Converting 0 to a
                  floating type yields 0.0 of that type (could be 0.0F (float), 0.0
                  (double), or 0.0L (long double)). Converting 0 to a pointer type
                  yields a null pointer. (I'm ignoring complex types, but the same
                  applies.) All these conversions yield the appropriate *value* of the
                  appropriate type, regardless of how it's represented. If a null
                  pointer is internally represented as 0xFFFFFFFF, converting 0 to a
                  pointer type still yields that null pointer value.
                  So far I am still initializing all my variables by hand. I could save a lot
                  of code if I removed all the to zero/NULL initializations for static
                  globals..
                  You might save some typing, but IMHO it's clearer to make the
                  initialization explicit if you're going to depend on the initial
                  value. You can save some typing for aggregate types by using
                  ``{ 0 }'' as the initializer; it's a consequence of the rules for
                  initializers that that particular form is a valid initializer
                  for any object type.
                  I am kind of worried about subtile breakage, though. Does a platform where 0
                  != NULL is true actually exist? Does the ANSI standard even allow such
                  platforms?
                  The representation of a null pointer may or may not be all-bits-zero,
                  but it can *always* be represented as 0 in C source.
                  And how far does this "intialized to 0" guarantee go? Are floating point
                  values guaranteed to be 0.0? Are all bytes of char array 0x00? What about
                  structures?
                  Yes, yes, yes.
                  I have never been bold enough to just do memset(structur e, 0,
                  sizeof(structur e)) if I wanted all members of the structure to be some kind
                  of zero (NULL pointer, 0 float, 0 byte, 0 int).
                  Good, that's not guaranteed to work.

                  Now, as it happens, you'll find that most implementations do choose to
                  use an all-bits-zero representation for floating-point 0.0 and for
                  null pointers. It makes a lot of things more convenient on most
                  modern hardware. For example, the system can place static object with
                  no explicit initialization in a segment that's set to all-bits-zero
                  when the program is loaded, saving space in the executable file. But
                  don't depend on it.
                  What should one do?
                  Keep learning.

                  --
                  Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                  Nokia
                  "We must do something. This is something. Therefore, we must do this."
                  -- Antony Jay and Jonathan Lynn, "Yes Minister"

                  Comment

                  • Keith Thompson

                    #10
                    Re: static and initialization rules or 0 is 0.0 is NULL

                    "copx" <copx@gazeta.pl writes:
                    "Ben Bacarisse" <ben.usenet@bsb .me.ukschrieb im Newsbeitrag
                    news:87mym4lk2l .fsf@bsb.me.uk. ..
                    [snip]
                    >>>>What should one do?
                    >>
                    >To the OP: one portable alternative is to write a zeroing function
                    >like this:
                    >>
                    >void zero_some_struc t(struct S *sp)
                    >{
                    > static struct S = {0};
                    > *sp = S;
                    >}
                    >>
                    >not always a good idea, but worth considering.
                    >
                    This was not portable the last time I checked. I once tried to compile some
                    C code that was full of the assumption that "structure = {0}" zeros all
                    members of the the structure. That works in GCC's "GNU C" mode (or at least
                    it used to work) but lcc-win32 rejected the code (at that time).
                    It's impossible to be sure without seeing both the exact code fed to
                    lcc-win and the exact diagnostic is produced, but your description
                    makes it sound like an lcc-win bug.
                    In the high
                    warning level/ANSI mode I use when compiling with GCC your code would
                    produce a "missing initializer" warning if struct S contains more than one
                    member.
                    Yes, gcc is trying to encourage you to provide explicit initializers
                    for all the members of the structure. It doesn't recognize "{ 0 }" as
                    a common idiom. IMHO it should.

                    --
                    Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                    Nokia
                    "We must do something. This is something. Therefore, we must do this."
                    -- Antony Jay and Jonathan Lynn, "Yes Minister"

                    Comment

                    • copx

                      #11
                      Re: static and initialization rules or 0 is 0.0 is NULL


                      "Keith Thompson" <kst-u@mib.orgschrie b im Newsbeitrag
                      news:ln7id8cyuf .fsf@nuthaus.mi b.org...
                      [snip]
                      It's impossible to be sure without seeing both the exact code fed to
                      lcc-win and the exact diagnostic is produced, but your description
                      makes it sound like an lcc-win bug.
                      That happened years ago. I don't remember the details.

                      [snip]
                      Yes, gcc is trying to encourage you to provide explicit initializers
                      for all the members of the structure. It doesn't recognize "{ 0 }" as
                      a common idiom. IMHO it should.
                      ...but as long as it doesn't I will avoid that construct. "missing
                      initializer" is a useful warning in general so I won't turn that off, and I
                      just hate seeing warnings when compiling my code even when I know that they
                      do not point out a problem.

                      I wrote an example to demonstrate the warning (in case that someone wants to
                      reproduce it):

                      struct S {int a,b,c;};

                      int main(void)
                      {
                      struct S foo = {0};

                      return foo.c;
                      }


                      gcc -W -Wall -Wextra -ansi -pedantic a.c

                      a.c: In function `main':
                      a.c:6: warning: missing initializer
                      a.c:6: warning: (near initialization for `foo.b')

                      This can get seriously ugly if you initialize many structures that way.



                      Comment

                      • vippstar@gmail.com

                        #12
                        Re: static and initialization rules or 0 is 0.0 is NULL

                        On Jun 2, 4:08 am, Ben Bacarisse <ben.use...@bsb .me.ukwrote:
                        Barry Schwarz <schwa...@dqel. comwrites:
                        On Mon, 2 Jun 2008 00:58:50 +0200, "copx" <c...@gazeta.pl wrote:
                        >
                        <snip your excellent explanations>
                        >
                        >values guaranteed to be 0.0? Are all bytes of char array 0x00? What about
                        >structures?
                        >
                        Yes. Only when CHAR_BIT is 8 (otherwise you need more zeros after the
                        x).
                        >
                        Surely 0x00 is just another way to write 0 and will zero initialise a
                        char of any width.
                        >
                        <snip>
                        >
                        >I have never been bold enough to just do memset(structur e, 0,
                        >sizeof(structu re)) if I wanted all members of the structure to be some kind
                        >of zero (NULL pointer, 0 float, 0 byte, 0 int).
                        >
                        While it will work on your system, it would not be portable.
                        >
                        >What should one do?
                        >
                        To the OP: one portable alternative is to write a zeroing function
                        like this:
                        >
                        void zero_some_struc t(struct S *sp)
                        {
                        static struct S = {0};
                        *sp = S;
                        >
                        }
                        >
                        not always a good idea, but worth considering.
                        This is also possible in C99:
                        void zerostruct(stru ct type *, typename); /* just to explain what is
                        passed to the macro */
                        #define zerostruct(s, type) (void)(*(s) = *(type[]){0})

                        Comment

                        • copx

                          #13
                          Re: static and initialization rules or 0 is 0.0 is NULL


                          "Keith Thompson" <kst-u@mib.orgschrie b im Newsbeitrag
                          news:lnbq2kczc2 .fsf@nuthaus.mi b.org...
                          [snip another detailed explanation]

                          Thanks. I think I get it now.
                          >What should one do?
                          >
                          Keep learning.
                          Given that I started programming in C more than a decade ago (only as a
                          part-time hobby, though), I am SO happy that I did not choose C++. I mean,
                          it has all the complexity of C + 10 times more of it. At this speed I
                          couldn't manage to completely master that language before dying of old age!
                          I MIGHT manage to master C before my 80th birthday (if I am lucky!).



                          Comment

                          • vippstar@gmail.com

                            #14
                            Re: static and initialization rules or 0 is 0.0 is NULL

                            On Jun 2, 6:42 am, "copx" <c...@gazeta.pl wrote:
                            "Keith Thompson" <ks...@mib.orgs chrieb im Newsbeitragnews :lnbq2kczc2.fsf @nuthaus.mib.or g...
                            [snip another detailed explanation]
                            >
                            Thanks. I think I get it now.
                            >
                            What should one do?
                            >
                            Keep learning.
                            >
                            Given that I started programming in C more than a decade ago (only as a
                            part-time hobby, though), I am SO happy that I did not choose C++. I mean,
                            it has all the complexity of C + 10 times more of it. At this speed I
                            couldn't manage to completely master that language before dying of old age!
                            I MIGHT manage to master C before my 80th birthday (if I am lucky!).
                            struct assignment isn't such a cryptic concept of the language.
                            See K&R2 6.2 for example. If you just want to be really good with C,
                            read K&R2!
                            Mastering, as in memorizing most of the standard, is another thing
                            which is rarely useful.
                            Such perfectionism will get into your way, as there are many
                            standards, not only C. (POSIX, IEEE 754 for example)
                            It's better to be familiar with the concepts and using a reference
                            when needed.

                            Comment

                            • Keith Thompson

                              #15
                              Re: static and initialization rules or 0 is 0.0 is NULL

                              "copx" <copx@gazeta.pl writes:
                              "Keith Thompson" <kst-u@mib.orgschrie b im Newsbeitrag
                              news:ln7id8cyuf .fsf@nuthaus.mi b.org...
                              [snip]
                              >It's impossible to be sure without seeing both the exact code fed to
                              >lcc-win and the exact diagnostic is produced, but your description
                              >makes it sound like an lcc-win bug.
                              >
                              That happened years ago. I don't remember the details.
                              >
                              [snip]
                              >Yes, gcc is trying to encourage you to provide explicit initializers
                              >for all the members of the structure. It doesn't recognize "{ 0 }" as
                              >a common idiom. IMHO it should.
                              >
                              ..but as long as it doesn't I will avoid that construct. "missing
                              initializer" is a useful warning in general so I won't turn that off, and I
                              just hate seeing warnings when compiling my code even when I know that they
                              do not point out a problem.
                              [...]

                              Fair enough.

                              You might also consider living with the warning and adding a comment
                              on the appropriate line, something like:

                              struct foo obj = { 0 }; /* ignore gcc "missing initializer" warning */

                              But eliminating all warnings certainly does make things easier than
                              eliminating most of them and having to confirm that the rest are ok.

                              On the other hand, compilers are free to warn about anything they
                              like. Making your code error-free for all compilers, including future
                              versions, is impossible.

                              --
                              Keith Thompson (The_Other_Keit h) kst-u@mib.org <http://www.ghoti.net/~kst>
                              Nokia
                              "We must do something. This is something. Therefore, we must do this."
                              -- Antony Jay and Jonathan Lynn, "Yes Minister"

                              Comment

                              Working...