473,405 Members | 2,310 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Structure initialization

Recently I was pinged in a code review about my use of the
initialization method
AStruct myStruct = { 0 } ;

Which initializes all elements of the myStruct to 0.

I was questioned on it because no one had seen this construct.
So i looked it up as best i could in the pointers to the Specification
that I find here and could not find any specific reference to this
construct. What i did find was reference to (paraphrasing) any values
not specified in the initializer are initialized to zero.

so it seems that the construct ={0}, sets the fisrst element to 0 and
since there are no more initializers present, all other structure
members are set to zero by default. Is this correct ?

Thanks
Joe
Jun 27 '08 #1
17 2649
On Jun 10, 12:53 pm, jb.si...@lmco.com wrote:
Recently I was pinged in a code review about my use of the
initialization method
AStruct myStruct = { 0 } ;

Which initializes all elements of the myStruct to 0.

I was questioned on it because no one had seen this construct.
So i looked it up as best i could in the pointers to the Specification
that I find here and could not find any specific reference to this
construct. What i did find was reference to (paraphrasing) any values
not specified in the initializer are initialized to zero.

so it seems that the construct ={0}, sets the fisrst element to 0 and
since there are no more initializers present, all other structure
members are set to zero by default. Is this correct ?

Thanks
Joe
Sort of. Here's the language from n1124:

"6.7.8. 21 If there are fewer initializers in a brace-enclosed list
than there are
elements or members of an aggregate, or fewer characters in a string
literal used
to initialize an array of known size than there are elements in the
array, the
remainder of the aggregate shall be initialized implicitly the same
as objects that
have static storage duration."

And the section on initialization of static objects:

"10 If an object that has automatic storage duration is not
initialized explicitly,
its value is indeterminate. If an object that has static storage
duration is not
initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or
unsigned) zero;
— if it is an aggregate, every member is initialized (recursively)
according to these rules;
— if it is a union, the first named member is initialized
(recursively) according to
these rules."
Jun 27 '08 #2
In article <13**********************************@26g2000hsk.g ooglegroups.com>,
<jb******@lmco.comwrote:
>Recently I was pinged in a code review about my use of the
initialization method
AStruct myStruct = { 0 } ;
>Which initializes all elements of the myStruct to 0.
>I was questioned on it because no one had seen this construct.
It does what you expected, and is, I believe, recognized by
experienced C programmers.

On the other hand, code reviews are often useful to catch constructs
that might be unclear to the student programmer who is going to
be asked to work on the code several years from now.

In my opinion, the code is correct and there is no value in changing
the code to explicitly initialize all the values "just in case" someone
doesn't understand the code; the explicit initialization would just
become a source of potential errors. But for future code maintenance,
it wouldn't hurt to put in a comment indicating that the entire
structure was being initialized; the comment code include a reference
to the specific section of the Standard for those who might be
a little too convinced that the code is mistaken.
--
"Let me live in my house by the side of the road --
It's here the race of men go by.
They are good, they are bad, they are weak, they are strong
Wise, foolish -- so am I;" -- Sam Walter Foss
Jun 27 '08 #3
On Jun 10, 1:53 pm, jb.si...@lmco.com wrote:
Recently I was pinged in a code review about my use of the
initialization method
AStruct myStruct = { 0 } ;

Which initializes all elements of the myStruct to 0.

I was questioned on it because no one had seen this construct.
So i looked it up as best i could in the pointers to the Specification
that I find here and could not find any specific reference to this
construct. What i did find was reference to (paraphrasing) any values
not specified in the initializer are initialized to zero.

so it seems that the construct ={0}, sets the fisrst element to 0 and
since there are no more initializers present, all other structure
members are set to zero by default. Is this correct ?

Thanks
Joe

I think you are right. The only "exception" I can think of is that
pointer members will be initialized to a null pointer constant which
may not be all-bit zero, but maybe a null pointer constant can be
considered as just a special kind of zero.
Jun 27 '08 #4
jb******@lmco.com wrote:
Recently I was pinged in a code review about my use of the
initialization method
AStruct myStruct = { 0 } ;

Which initializes all elements of the myStruct to 0.

I was questioned on it because no one had seen this construct.
So i looked it up as best i could in the pointers to the Specification
that I find here and could not find any specific reference to this
construct. What i did find was reference to (paraphrasing) any values
not specified in the initializer are initialized to zero.

so it seems that the construct ={0}, sets the fisrst element to 0 and
since there are no more initializers present, all other structure
members are set to zero by default. Is this correct ?
...
Yes, that's absolutely correct (with the exception of _unnamed_ members,
which are left uninitialized). The construct you used is a
well-recognized zero-initialization idiom in C.

The fact that "no one had seen this construct" in your team simply means
that other members haven't learned it yet.

--
Best regards,
Andrey Tarasevich
Jun 27 '08 #5
On Tue, 10 Jun 2008 10:53:14 -0700, jb.simon wrote:
so it seems that the construct ={0}, sets the fisrst element to 0 and
since there are no more initializers present, all other structure
members are set to zero by default. Is this correct ?
That is correct. And when the first member is an array or structure (or a
union starting with one of these), it applies to the remaining members or
elements of the first member as well. That is, when X is a simple integer
constant, possibly 0, possibly something else,

struct A {
struct B {
int a, b, c;
} s;
int d;
} a = {X};

initialises a.s.a to X, while a.s.b, a.s.c, and a.d are all given their
default values of 0.
Jun 27 '08 #6
John Bode <jo*******@my-deja.comwrites:
[snip]
Sort of. Here's the language from n1124:
[snip]

You're still using n1124? n1256 is more current.

http://www.open-std.org/jtc1/sc22/wg...docs/n1256.pdf

--
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 27 '08 #7
Walter Roberson wrote:
In article <13**********************************@26g2000hsk.g ooglegroups.com>,
<jb******@lmco.comwrote:
>Recently I was pinged in a code review about my use of the
initialization method
AStruct myStruct = { 0 } ;
>Which initializes all elements of the myStruct to 0.
>I was questioned on it because no one had seen this construct.

It does what you expected, and is, I believe, recognized by
experienced C programmers.

On the other hand, code reviews are often useful to catch constructs
that might be unclear to the student programmer who is going to
be asked to work on the code several years from now.

In my opinion, the code is correct and there is no value in changing
the code to explicitly initialize all the values "just in case" someone
doesn't understand the code; the explicit initialization would just
become a source of potential errors. But for future code maintenance,
it wouldn't hurt to put in a comment indicating that the entire
structure was being initialized; the comment code include a reference
to the specific section of the Standard for those who might be
a little too convinced that the code is mistaken.
If the only reason that a programmer
can't understand a particular C code construct,
is because the programmer doesn't know enough C,
then it's time to learn more C.

What kind of a programmer needs to be told that?
Are child labor laws no longer being enforced?

--
pete
Jun 27 '08 #8
pete wrote:

<snip>
If the only reason that a programmer
can't understand a particular C code construct,
is because the programmer doesn't know enough C,
then it's time to learn more C.
Only if your boss gives you time off to do so.

<snip>

Jun 27 '08 #9
In article <W8******************************@earthlink.com> ,
pete <pf*****@mindspring.comwrote:
>If the only reason that a programmer
can't understand a particular C code construct,
is because the programmer doesn't know enough C,
then it's time to learn more C.
>What kind of a programmer needs to be told that?
Are child labor laws no longer being enforced?
When it comes to programming... No, they aren't.

Some of my programming-related skills are -relatively- rare
even amongst programmers, and as a result I earn a decent
(but not rich) living from my work. But I grew up in an era
when my father literally maintained *mechanical* calculators
(and manual typewriters and non-programmable electric typewriters),
together with a few early electronic calculators with very basic
functionality and Nixie tubes (the mechanical calculators had
more functionality!). My nieces and nephews are growing up in
an era when it isn't uncommon for a five-year-old to be better at
using computers than their parents.

High school computer multi-millionares are a reality: the young have a
grasp of the potential (and the likely social desirability) of computer
systems that I will likely never have. So Yes, children *are*
programming these days, and are producing some amazing things.
But beyond that... there will always be a steady stream of the
marginally competant who don't know enough to look in a reference book.
And if the university students I often see posting in another technical
newsgroup are typical of the modern generation, then it appears that
we have somehow managed to raise a generation of programmers who
consider it to be beneath them to do any research, convinced that
they are *owed* complete code to do <whatever>, annoyed that they
even have to ask once for it... and yet convinced that whatever they
"know" is right and anything contra-indicative of what they "know"
is wrong (or was *deliberately* mis-designed.) A generation of
Entitlement to other people's skills and labour, and one that
too often has an antipathy to learning. It is a generation that
is proving surprisingly difficult to teach. :(

Thus, including a comment with a reference to the Standard can be
form of self-defence: the barbarians likely will not stop to -read-
the Standard before complaining about your code, but you can
then respond, "And what did that section of the Standard say
about the situation??" instead of having to spend your time writing
memos pointing out the relevant section, and spending your time
defending your programming style, and being written up as
"not a team player" and whatever.
--
"The whole history of civilization is strewn with creeds and
institutions which were invaluable at first, and deadly
afterwards." -- Walter Bagehot
Jun 27 '08 #10
Yunzhong said:
On Jun 10, 1:53 pm, jb.si...@lmco.com wrote:
<snip>
>>
so it seems that the construct ={0}, sets the fisrst element to 0 and
since there are no more initializers present, all other structure
members are set to zero by default. Is this correct ?


I think you are right. The only "exception" I can think of is that
pointer members will be initialized to a null pointer constant which
may not be all-bit zero,
It doesn't matter - it's not an exception regardless of the representation
of a null pointer. The static default initialisers that apply here are 0
for integer types, 0.0 for floating point types, and NULL for pointer
types.
but maybe a null pointer constant can be
considered as just a special kind of zero.
Yes, sort of.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jun 27 '08 #11
Richard Heathfield <rj*@see.sig.invalidwrites:
Yunzhong said:
>On Jun 10, 1:53 pm, jb.si...@lmco.com wrote:
<snip>
>>>
so it seems that the construct ={0}, sets the fisrst element to 0 and
since there are no more initializers present, all other structure
members are set to zero by default. Is this correct ?


I think you are right. The only "exception" I can think of is that
pointer members will be initialized to a null pointer constant which
may not be all-bit zero,

It doesn't matter - it's not an exception regardless of the representation
of a null pointer. The static default initialisers that apply here are 0
for integer types, 0.0 for floating point types, and NULL for pointer
types.
Yes.

Another way to look at it is that the default initializer is simply 0
for *all* scalar types, converted in each case to the appropriate
type.

[...]

--
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 27 '08 #12
Keith Thompson wrote:
Richard Heathfield <rj*@see.sig.invalidwrites:
>Yunzhong said:
>>On Jun 10, 1:53 pm, jb.si...@lmco.com wrote:
<snip>
>>>so it seems that the construct ={0}, sets the fisrst element to 0 and
since there are no more initializers present, all other structure
members are set to zero by default. Is this correct ?

I think you are right. The only "exception" I can think of is that
pointer members will be initialized to a null pointer constant which
may not be all-bit zero,
It doesn't matter - it's not an exception regardless of the representation
of a null pointer. The static default initialisers that apply here are 0
for integer types, 0.0 for floating point types, and NULL for pointer
types.

Yes.

Another way to look at it is that the default initializer is simply 0
for *all* scalar types, converted in each case to the appropriate
type.
Another way to look at it is that the default initializer is simply {0}
for *all* types.

--
pete
Jun 27 '08 #13
santosh wrote:
pete wrote:
>If the only reason that a programmer
can't understand a particular C code construct,
is because the programmer doesn't know enough C,
then it's time to learn more C.

Only if your boss gives you time off to do so.
Do I understand you to mean
that if your boss saw you reading a C reference
while you were supposed to be writing C code,
that your boss would be displeased?

That notion seems bizarre to me.
What do you really mean?

--
pete
Jun 27 '08 #14
Walter Roberson wrote:
>
.... snip ...
>
Some of my programming-related skills are -relatively- rare
even amongst programmers, and as a result I earn a decent
(but not rich) living from my work. But I grew up in an era
when my father literally maintained *mechanical* calculators
(and manual typewriters and non-programmable electric typewriters),
together with a few early electronic calculators with very basic
functionality and Nixie tubes (the mechanical calculators had
more functionality!). My nieces and nephews are growing up in
an era when it isn't uncommon for a five-year-old to be better at
using computers than their parents.
I deny that functionallity allegation. :-) See:

<http://cbfalconer.home.att.net/firstpc/>

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #15
John Bode wrote:
jb.si...@lmco.com wrote:
>Recently I was pinged in a code review about my use of the
initialization method
AStruct myStruct = { 0 } ;

Which initializes all elements of the myStruct to 0.
.... snip ...
>>
so it seems that the construct ={0}, sets the fisrst element to
0 and since there are no more initializers present, all other
structure members are set to zero by default. Is this correct ?

Sort of. Here's the language from n1124:

"6.7.8. 21 If there are fewer initializers in a brace-enclosed list
than there are
elements or members of an aggregate, or fewer characters in a string
literal used
to initialize an array of known size than there are elements in the
array, the
remainder of the aggregate shall be initialized implicitly the same
as objects that
have static storage duration."

And the section on initialization of static objects:

"10 If an object that has automatic storage duration is not
initialized explicitly,
its value is indeterminate. If an object that has static storage
duration is not
initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or
unsigned) zero;
— if it is an aggregate, every member is initialized (recursively)
according to these rules;
— if it is a union, the first named member is initialized
(recursively) according to
these rules."
A little more readable if taken from N869.txt:

[#21] If there are fewer initializers in a brace-enclosed
list than there are elements or members of an aggregate, or
fewer characters in a string literal used to initialize an
array of known size than there are elements in the array,
the remainder of the aggregate shall be initialized
implicitly the same as objects that have static storage
duration.

and

[#10] If an object that has automatic storage duration is
not initialized explicitly, its value is indeterminate. If
an object that has static storage duration is not
initialized explicitly, then:

-- if it has pointer type, it is initialized to a null
pointer;
-- if it has arithmetic type, it is initialized to
(positive or unsigned) zero;
-- if it is an aggregate, every member is initialized
(recursively) according to these rules;
-- if it is a union, the first named member is initialized
(recursively) according to these rules.

See <http://cbfalconer.home.att.net/download/n869_txt.bz2>

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #16
pete wrote:
santosh wrote:
>pete wrote:
>>If the only reason that a programmer
can't understand a particular C code construct,
is because the programmer doesn't know enough C,
then it's time to learn more C.

Only if your boss gives you time off to do so.

Do I understand you to mean
that if your boss saw you reading a C reference
while you were supposed to be writing C code,
that your boss would be displeased?

That notion seems bizarre to me.
What do you really mean?
I mean that here, outside of transnational companies, it's very unusual
in the middle to low end jobs here for your "boss" to let you take time
off, even if it might benefit your work efficiency in the long run.

Specifically, with regards to C, clc's standards are, IME _very_ high.
For example in the code bases I have had the opportunity to examine I
have never once come across the form of structure initialisation
demonstrated in this thread.

Jun 27 '08 #17
Harald van Dijk wrote:
On Tue, 10 Jun 2008 10:53:14 -0700, jb.simon wrote:
>so it seems that the construct ={0}, sets the fisrst element to 0 and
since there are no more initializers present, all other structure
members are set to zero by default. Is this correct ?

That is correct. And when the first member is an array or structure (or a
union starting with one of these), it applies to the remaining members or
elements of the first member as well. That is, when X is a simple integer
constant, possibly 0, possibly something else,

struct A {
struct B {
int a, b, c;
} s;
int d;
} a = {X};

initialises a.s.a to X, while a.s.b, a.s.c, and a.d are all given their
default values of 0.
Thanks for all of the replies.

I forwarded the relevant parts of the standard to the person who
commented, indicating it *is* standard, and then I also changed my code
to add functions (4 of them) to explicitly initialize all fields to 0.
It was not a big deal, however, now if any of those structures change
the appropriate initialization function also needs to change.

In a way this is really not so bad, because this supports an setting the
variables to non zero at initialization if desired.

P.S. The reason I put these in a function is these structures can be
kinda large (50-100 members) and i didn't want to clutter the caller
with all of the initialization. To me it makes it harder to read the
function if you have lines and lines of initializaiton code.

Thanks All !
Joe

Jun 27 '08 #18

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

Similar topics

2
by: Kevin P. Fleming | last post by:
I've got an enum and a structure: enum option_type { O_STRING, O_BOOL, O_NUMBER }; struct option_s { char *name;
9
by: Skybuck Flying | last post by:
Hello, What does Const mean in this c structure ? and what is the delphi equivalent ? I think const struct just means it can't be modified... is that correct ? Struct { Type1 Field1;...
2
by: kimimaro | last post by:
hi I wonder if array can be work along with structure? Below are the declaration of my structure struct employee{ char ID; char Name; char Department;
14
by: Stef | last post by:
Hello, I have a question: Is it possible to init a 2d array of structures to zero ? For example with array I do. int array = {0} but:
5
by: aarklon | last post by:
Hi all, why the following structure initialization is not valid #include<stdio.h> struct rec { char name; int age; };
11
by: aaragon | last post by:
Hi everyone. I'm trying to write a class with policy based design (Alexandrescu's Modern C++ Design). I'm not a programmer but an engineer so this is kind of hard for me. Through the use of...
4
by: hobbes992 | last post by:
Howdy folks, I've been working on a c project, compiling using gcc, and I've reached a problem. The assignment requires creation of a two-level directory file system. No files have to be added or...
4
by: koffee | last post by:
Hi people, I've got a question on global structure initialization. A global variable like int can be explicitly initialized as: int Global = 1; But how can I explicitly initialize a...
14
by: Bill Reid | last post by:
OK, let's say that have a function menu structure declaration like this (since I basically do): typedef struct function_item { char *descrip; void(*function)(void); } t_function_item; ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
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...

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.