By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,187 Members | 1,069 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,187 IT Pros & Developers. It's quick & easy.

static and initialization rules or 0 is 0.0 is NULL

P: n/a
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(structure, 0,
sizeof(structure)) 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?

Jun 1 '08 #1
Share this Question
Share on Google+
17 Replies


P: n/a
On Mon, 2 Jun 2008 00:58:50 +0200, "copx" <co**@gazeta.plwrote:
>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(structure, 0,
sizeof(structure)) 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
Jun 1 '08 #2

P: n/a

"copx" <co**@gazeta.plwrote in message
news:g1**********@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
Jun 2 '08 #3

P: n/a
Barry Schwarz <sc******@dqel.comwrites:
On Mon, 2 Jun 2008 00:58:50 +0200, "copx" <co**@gazeta.plwrote:
<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(structure, 0,
sizeof(structure)) 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_struct(struct S *sp)
{
static struct S = {0};
*sp = S;
}

not always a good idea, but worth considering.

--
Ben.
Jun 2 '08 #4

P: n/a

"Bartc" <bc@freeuk.comschrieb im Newsbeitrag
news:6D*****************@text.news.virginmedia.com ...
>
"copx" <co**@gazeta.plwrote in message
news:g1**********@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).
Jun 2 '08 #5

P: n/a
Bartc wrote:
"copx" <co**@gazeta.plwrote in message
news:g1**********@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
Jun 2 '08 #6

P: n/a

"Ben Bacarisse" <be********@bsb.me.ukschrieb im Newsbeitrag
news:87************@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_struct(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.

Jun 2 '08 #7

P: n/a

"copx" <co**@gazeta.plschrieb im Newsbeitrag
news:g1**********@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.

Jun 2 '08 #8

P: n/a
"copx" <co**@gazeta.plwrites:
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(structure, 0,
sizeof(structure)) 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_Keith) ks***@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"
Jun 2 '08 #9

P: n/a
"copx" <co**@gazeta.plwrites:
"Ben Bacarisse" <be********@bsb.me.ukschrieb im Newsbeitrag
news:87************@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_struct(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_Keith) ks***@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"
Jun 2 '08 #10

P: n/a

"Keith Thompson" <ks***@mib.orgschrieb im Newsbeitrag
news:ln************@nuthaus.mib.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.

Jun 2 '08 #11

P: n/a
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.plwrote:

<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(structure, 0,
sizeof(structure)) 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_struct(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(struct type *, typename); /* just to explain what is
passed to the macro */
#define zerostruct(s, type) (void)(*(s) = *(type[]){0})
Jun 2 '08 #12

P: n/a

"Keith Thompson" <ks***@mib.orgschrieb im Newsbeitrag
news:ln************@nuthaus.mib.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!).

Jun 2 '08 #13

P: n/a
On Jun 2, 6:42 am, "copx" <c...@gazeta.plwrote:
"Keith Thompson" <ks...@mib.orgschrieb im Newsbeitragnews:ln************@nuthaus.mib.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!).
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.
Jun 2 '08 #14

P: n/a
"copx" <co**@gazeta.plwrites:
"Keith Thompson" <ks***@mib.orgschrieb im Newsbeitrag
news:ln************@nuthaus.mib.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_Keith) ks***@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"
Jun 2 '08 #15

P: n/a
On Mon, 02 Jun 2008 02:08:50 +0100, Ben Bacarisse
<be********@bsb.me.ukwrote:
>Barry Schwarz <sc******@dqel.comwrites:
>On Mon, 2 Jun 2008 00:58:50 +0200, "copx" <co**@gazeta.plwrote:
<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.
Any constant expression that evaluates to 0 will do that. In the
context of what the OP was writing, I took it to mean he expected a
char to be exactly 8 bits.
Remove del for email
Jun 2 '08 #16

P: n/a
On Mon, 2 Jun 2008 04:49:07 +0200, "copx" <co**@gazeta.plwrote:
>
"Bartc" <bc@freeuk.comschrieb im Newsbeitrag
news:6D*****************@text.news.virginmedia.co m...
>>
"copx" <co**@gazeta.plwrote in message
news:g1**********@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).
That is not the claim you made in your original post. You claimed
that initialization
static int foo = 0;
created a lot more code than default
static int foo;

You may have meant that assignments generate more code than
initialization (as you describe in this post) but it is not what you
wrote originally.
Remove del for email
Jun 2 '08 #17

P: n/a

<vi******@gmail.comschrieb im Newsbeitrag
news:54**********************************@j22g2000 hsf.googlegroups.com...
On Jun 2, 6:42 am, "copx" <c...@gazeta.plwrote:
>"Keith Thompson" <ks...@mib.orgschrieb im
Newsbeitragnews:ln************@nuthaus.mib.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!).
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!
I read that book years ago. Remembering everything is another matter..
Jun 2 '08 #18

This discussion thread is closed

Replies have been disabled for this discussion.