473,804 Members | 3,447 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

struct member initialization - member by member?!

Hi

I discovered that if you declare a structure (and not 'new()' it) you
can then separately initialize its members and the compiler counts
those separate statements as a full initialization. That struck me as
a bit odd really as I would have thought it would have only bothered
about 'tracking' an 'atomic'/'complete' (via 'new()') initialization
not doing it 'bit by it'!!! Any comments? Seems a bit of an overhead
tracking memberwise initialization doesn't it? Any C# compiler people
out there?

Hoping for some comments to show me that this isn't such a weird thing
please.

Emma Middlebrook
em************* *@fastmail.fm

struct Value
{
public int x;
public int y;
}

Value v2;
v2.x = 6; // v2 can not be used yet as 'unassigned' ...
v2.y = 7; // v2 can now be used as all its parts are initialized.
Nov 15 '05 #1
10 8649
emma middlebrook <em************ **@fastmail.fm> wrote:
I discovered that if you declare a structure (and not 'new()' it) you
can then separately initialize its members and the compiler counts
those separate statements as a full initialization. That struck me as
a bit odd really as I would have thought it would have only bothered
about 'tracking' an 'atomic'/'complete' (via 'new()') initialization
not doing it 'bit by it'!!! Any comments? Seems a bit of an overhead
tracking memberwise initialization doesn't it? Any C# compiler people
out there?


Why would it be an overhead? Or rather, why do you care about the
overhead which only exists at *compile* time? I'd rather the compiler
kept track of a few extra things to prevent bugs, if it doesn't take
any extra time at runtime.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 15 '05 #2
If you go through the documentation and specs.. you'll see that it says
'structs that are not initilized cannot be accessed or used'. This
doesn't imply that the runtime would do any sort of tracking, in fact,
the compiler will plainly give you a message that there's an error and
won't compile (till you've initialized struct data before using it).
So.. it only checks for validity upon struct data being accessed. Have a
look at the following sample program:

public struct Point
{
public int x, y;

public Point(int p1, int p2)
{
x = p1;
y = p2;
}
}

class MyClass {
static void Main(string args[]) {
Point p;
Console.WriteLi ne("X is: {0}", p.x);

// Compiler will perform a check hede and will abort..

p.x;
Console.WriteLi ne("X is: {0}", p.x);

/*
if you comment out the preceding statement, the program will work and
compile. Notice I didn't initialize y and it still worked. This shows
that the compiler doesn't check for 'every' field that's not initialized
but only when a field is being accessed */

}
}
-Andre

emma middlebrook wrote:
Hi

I discovered that if you declare a structure (and not 'new()' it) you
can then separately initialize its members and the compiler counts
those separate statements as a full initialization. That struck me as
a bit odd really as I would have thought it would have only bothered
about 'tracking' an 'atomic'/'complete' (via 'new()') initialization
not doing it 'bit by it'!!! Any comments? Seems a bit of an overhead
tracking memberwise initialization doesn't it? Any C# compiler people
out there?

Hoping for some comments to show me that this isn't such a weird thing
please.

Emma Middlebrook
em************* *@fastmail.fm

struct Value
{
public int x;
public int y;
}

Value v2;
v2.x = 6; // v2 can not be used yet as 'unassigned' ...
v2.y = 7; // v2 can now be used as all its parts are initialized.


Nov 15 '05 #3
Exactly - another good point made :)

-Andre

Jon Skeet wrote:
emma middlebrook <em************ **@fastmail.fm> wrote:
I discovered that if you declare a structure (and not 'new()' it) you
can then separately initialize its members and the compiler counts
those separate statements as a full initialization. That struck me as
a bit odd really as I would have thought it would have only bothered
about 'tracking' an 'atomic'/'complete' (via 'new()') initialization
not doing it 'bit by it'!!! Any comments? Seems a bit of an overhead
tracking memberwise initialization doesn't it? Any C# compiler people
out there?

Why would it be an overhead? Or rather, why do you care about the
overhead which only exists at *compile* time? I'd rather the compiler
kept track of a few extra things to prevent bugs, if it doesn't take
any extra time at runtime.


Nov 15 '05 #4
Another reason is that structs don't have inheritance and are allocated on
the stack (until they're boxed at which time they get copied onto the heap).
When they're on the stack, they can really be though of as just a grouping
of nested locals on the stack. Until you box them or pass them to some
other method the compiler treats them as such and allows each member to be
independently initialized and used accordingly. This allows methods to
dynamically initialize certain members based on calculated information,
rather than requiring heavy handed stuff like forcing you to zero initialize
everything and then overwrite that with the real value later (plus it
prevents you from accessing the member before the 'real value' has been
set). Now when you pass that struct to some other method or cause it to be
boxed, the method being called has the implicit contract that input
parameters are fully initialized, and so at that point the compiler requires
that all members have been initialized. A similar statement is true for
boxing.

--
--Grant
This posting is provided "AS IS" with no warranties, and confers no rights.
"emma middlebrook" <em************ **@fastmail.fm> wrote in message
news:e2******** *************** ***@posting.goo gle.com...
Hi

I discovered that if you declare a structure (and not 'new()' it) you
can then separately initialize its members and the compiler counts
those separate statements as a full initialization. That struck me as
a bit odd really as I would have thought it would have only bothered
about 'tracking' an 'atomic'/'complete' (via 'new()') initialization
not doing it 'bit by it'!!! Any comments? Seems a bit of an overhead
tracking memberwise initialization doesn't it? Any C# compiler people
out there?

Hoping for some comments to show me that this isn't such a weird thing
please.

Emma Middlebrook
em************* *@fastmail.fm

struct Value
{
public int x;
public int y;
}

Value v2;
v2.x = 6; // v2 can not be used yet as 'unassigned' ...
v2.y = 7; // v2 can now be used as all its parts are initialized.

Nov 15 '05 #5
100
Hi Grant,

"> Another reason is that structs don't have inheritance and are allocated
on
the stack (until they're boxed at which time they get copied onto the heap).

Not quite accurate, though. ValuTypes can be created unboxed in the managed
heap as part of an reference type members.
This allows methods to
dynamically initialize certain members based on calculated information,
rather than requiring heavy handed stuff like forcing you to zero initialize everything and then overwrite that with the real value later (plus it
prevents you from accessing the member before the 'real value' has been
set).


In the case of creating value type in managed heap all members of the value
type is guaranteed to be zeroed. which means: reference type is set to null,
scalar to 0 and boolean to false. I this particular case c# will not
complain if you use the value without prior initialization.

To be completely correct it will warn you that you gonna use the default
value of the member.
Now when you pass that struct to some other method or cause it to be

B\rgds
100
Nov 15 '05 #6
Jon Skeet <sk***@pobox.co m> wrote in message news:<MP******* *************** **@news.microso ft.com>...
emma middlebrook <em************ **@fastmail.fm> wrote:
I discovered that if you declare a structure (and not 'new()' it) you
can then separately initialize its members and the compiler counts
those separate statements as a full initialization. That struck me as
a bit odd really as I would have thought it would have only bothered
about 'tracking' an 'atomic'/'complete' (via 'new()') initialization
not doing it 'bit by it'!!! Any comments? Seems a bit of an overhead
tracking memberwise initialization doesn't it? Any C# compiler people
out there?


Why would it be an overhead? Or rather, why do you care about the
overhead which only exists at *compile* time? I'd rather the compiler
kept track of a few extra things to prevent bugs, if it doesn't take
any extra time at runtime.


Why do I care: to broaden my knowledge and better understand what is
happening. I didn't say I was unhappy about any compile-time cost -
just that it seemed surprising.

Thanks

Emma Middlebrook
em************* *@fastmail.fm
Nov 15 '05 #7
Andre <fo********@hot mail.com> wrote in message news:<3F******* *******@hotmail .com>...
If you go through the documentation and specs.. you'll see that it says
'structs that are not initilized cannot be accessed or used'. This
doesn't imply that the runtime would do any sort of tracking, in fact,
the compiler will plainly give you a message that there's an error and
won't compile (till you've initialized struct data before using it).
So.. it only checks for validity upon struct data being accessed. Have a
look at the following sample program:


Who mentioned the run-time tracking anything? Also, as you point out
in your little code snippet, the doc/specs aren't correct if they say
what you quote above - it's possible to use any member of a struct as
long as it's been initialized. As I said, I find it weird that it
allows parts of a partially initialized type to be used. Are you and
Jon both saying you find this quite natural and expected in a language
making quite an effort to stop the programmer shooting themselves in
the foot? It's not a big deal but I was surprised to find that
partially initialized types could be used.

Emma Middlebrook
em************* *@fastmail.fm
Nov 15 '05 #8
Andre <fo********@hot mail.com> wrote in message news:<3F******* *******@hotmail .com>...
If you go through the documentation and specs.. you'll see that it says
'structs that are not initilized cannot be accessed or used'. This
doesn't imply that the runtime would do any sort of tracking, in fact,
the compiler will plainly give you a message that there's an error and
won't compile (till you've initialized struct data before using it).
So.. it only checks for validity upon struct data being accessed. Have a
look at the following sample program:


Who mentioned the run-time tracking anything? Also, as you point out
in your little code snippet, the doc/specs aren't correct if they say
what you quote above - it's possible to use any member of a struct as
long as it's been initialized. As I said, I find it weird that it
allows parts of a partially initialized type to be used. Are you and
Jon both saying you find this quite natural and expected in a language
making quite an effort to stop the programmer shooting themselves in
the foot? It's not a big deal but I was surprised to find that
partially initialized types could be used.

Emma Middlebrook
em************* *@fastmail.fm
Nov 15 '05 #9
emma middlebrook <em************ **@fastmail.fm> wrote:
Thanks for your reply - I think you have hit on the real nub - I would
like to think of a class/struct as a type that should be either
uninitialized or initialized completely. I don't like this 'weak' idea
of a struct being a loose grouping of members and that its parts can
be used if those parts happened to have been initialized. However, I'm
really glad you mentioned the point that once the struct is passed to
some other method then it has to completely initialized. I'm happy
enough now and have confirmed this to be true both for passing structs
by value and passing structs by reference. This is good news and, to
be honest, I don't care that you can fiddle with the parts and use the
parts 'locally'.


I think it's actually rather helpful that you can fiddle with the parts
locally - you may want to set up one variable based on some
calculations with another, for instance. It would be a pain if you were
forced to use a separate local variable for that.

On the other hand, I'm not entirely sure how this works when the struct
uses properties instead of public fields... I guess you've got to use
"new" in that case.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 15 '05 #10

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

Similar topics

1
3940
by: matro | last post by:
hi there, I have the following struct in my class: class CTbStDialog : public CDialog { public: int fooVar, fooVar2; ... //other foo variables...
3
7663
by: sathyashrayan | last post by:
The standard confirms that the following initialization of a struct struct node { --- --- } struct node var = {NULL};
2
3062
by: Immo Birnbaum | last post by:
Hi, I'm trying to solve a programming lab assignment for my college C programming course, but as they taught us two semesters of Java before teaching us any C, I'm having problems with all the aspects of pointers. I'd appreciate if anybody could help me with the following problem: I tried to learn how to use malloc, free, and the * and & operators. I started with a few simple lines of code like:
5
8735
by: Chris | last post by:
Hi, I don't get the difference between a struct and a class ! ok, I know that a struct is a value type, the other a reference type, I understand the technical differences between both, but conceptually speaking : when do I define something as 'struct' and when as 'class' ? for example : if I want to represent a 'Time' thing, containing : - data members : hours, mins, secs
74
16041
by: Zytan | last post by:
I have a struct constructor to initialize all of my private (or public readonly) fields. There still exists the default constructor that sets them all to zero. Is there a way to remove the creation of this implicit default constructor, to force the creation of a struct via my constructor only? Zytan
18
9129
by: Ehud Shapira | last post by:
Is it possible to have a declaration of a struct pointer initialized to an unnamed struct? (I'm only concerned with static/global variables, if it matters.) I'm trying to do something like: struct st_a { int i, j; };
6
15122
by: Daniel Rudy | last post by:
Hello Group. Please consider the following code: /* this table is used in the wipedevice routine */ static const struct wipe_t { uchar wte; /* wipe table entry */ } wipetable = { {0x00, 0x00, 0x00},
2
8375
by: Antti Karanta | last post by:
Hi! Is it possible to inline initialize a struct whose one member is a string array of arbitrary length (terminated w/ a NULL ptr)? What I mean is something like this: typedef struct { char** x ; int y ;
5
11676
by: ssylee | last post by:
I'm not sure if I can initialize members of a struct the lazy way. For example, let's say I have a struct defined as below: typedef struct _ABC { BOOL A; BOOL B; BOOL C; } ABC;
0
9711
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
10343
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10331
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
10087
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
7631
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
5667
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4306
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
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.