473,651 Members | 3,012 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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?

Jun 1 '08 #1
17 4432
On Mon, 2 Jun 2008 00:58:50 +0200, "copx" <co**@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
Jun 1 '08 #2

"copx" <co**@gazeta.pl wrote 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
Barry Schwarz <sc******@dqel. comwrites:
On Mon, 2 Jun 2008 00:58:50 +0200, "copx" <co**@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.
Jun 2 '08 #4

"Bartc" <bc@freeuk.coms chrieb im Newsbeitrag
news:6D******** *********@text. news.virginmedi a.com...
>
"copx" <co**@gazeta.pl wrote 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
Bartc wrote:
"copx" <co**@gazeta.pl wrote 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

"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_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.

Jun 2 '08 #7

"copx" <co**@gazeta.pl schrieb 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
"copx" <co**@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) 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
"copx" <co**@gazeta.pl writes:
"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_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) 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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2199
by: roger | last post by:
Here's a weird one... The code below works just fine when I build in DEBUG mode. Today, I tried to build my solution in RELEASE mode, and immediately fell over this problem - apparently something in the order or sequencing or something regarding static initialization. Consider this class, which implements a singleton pattern:
1
4617
by: Qin Chen | last post by:
I will present very long code, hope someone will read it all, and teach me something like tom_usenet. This question comes to me when i read <<Think in C++>> 2nd, chapter 10 , name control, section "Static initialization dependency". There is a example to show how to solve the prolem involved with a technique first poineered by Jerry Schwarz while creating the iostream library (because the definitions for cin, cout, and cerr are static...
4
2533
by: marvind | last post by:
I think I am running into the static initialization problem but I do not understand why. I am trying to parse a configuration file. To make this parser generic I register callbacks for various section keywords in the configuration file. I want to share this map of callbacks across multiple instances of the config file (for example, when I merge two files). Whenever I introduce a new section in the configuration file, I define a new class...
1
2226
by: bvisscher | last post by:
I posted this recently in microsoft.public.vc.language and was redirected here. I also searched this ng and found some relavant threads. The most relavent I found was: http://groups.google.com/group/microsoft.public.dotnet.languages.vc/browse_frm/thread/dac4c07f8678cc0a/32919fdc1ee07313?q=static+initialization+mixed&rnum=2#32919fdc1ee07313
3
5845
by: Steve Folly | last post by:
Hi, I had a problem in my code recently which turned out to be the 'the "static initialization order fiasco"' problem (<http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12>) The FAQ section describes a solution using methods returning references to static objects. But consider:
20
6083
by: JohnQ | last post by:
The way I understand the startup of a C++ program is: A.) The stuff that happens before the entry point. B.) The stuff that happens between the entry point and the calling of main(). C.) main(). So, if the above is OK, does static initialization occur during A or B? What happens during A?
5
1377
by: Chris Thomasson | last post by:
Here is a way that you can "automate" static initialization of arrays with customized data. Here is a quick example: -------------------- #include <stdio.h> #include <stddef.h> #include <assert.h>
23
252
by: copx | last post by:
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...
0
8361
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8807
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8466
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8584
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6158
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5615
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4144
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1912
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1588
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.