473,748 Members | 10,048 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

unions: initialization and assignment


Hello,

I would like to know whether the following C fragment is legal in
standard C and behaves as intended under conforming implementations ...

union foo {
char c;
double d;
};

int main(void) {
union foo x;
x.d = 3.3;
printf("%g\n", x.d);
union foo y = x;
printf("%g\n", y.d);
union foo z;
z = y;
printf("%g\n", z.d);
}

The above syntactic sugar could save a few characters of code if legal
since union members would not have to be explicitly mentioned in the code.

Output (gcc 3.2.2):

3.3
3.3
3.3

Thanks!

Neil

Nov 13 '05 #1
6 13382
On Wed, 17 Sep 2003 01:14:04 -0230, Neil Zanella <nz******@cs.mu n.ca>
wrote in comp.lang.c:

Hello,

I would like to know whether the following C fragment is legal in
standard C and behaves as intended under conforming implementations ...

union foo {
char c;
double d;
};

int main(void) {
union foo x;
x.d = 3.3;
printf("%g\n", x.d);
union foo y = x;
printf("%g\n", y.d);
union foo z;
z = y;
printf("%g\n", z.d);
}

The above syntactic sugar could save a few characters of code if legal
since union members would not have to be explicitly mentioned in the code.

Output (gcc 3.2.2):

3.3
3.3
3.3

Thanks!

Neil


What exactly are you trying to get at with all of these questions
about unions?

You can assign one union to another in C, this has been part of the
language since the original 1989 ANSI standard.

A union can contain only one member at a time, namely the one that was
last assigned to. If you assign that union to another union, that
same member is still valid in the new union and has the same value.

What is there that you think is so unusual about unions that you would
not expect that code?

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Nov 13 '05 #2
On Wed, 17 Sep 2003 01:14:04 -0230
Neil Zanella <nz******@cs.mu n.ca> wrote:

Hello,

I would like to know whether the following C fragment is legal in
standard C and behaves as intended under conforming implementations ...

union foo {
char c;
double d;
};
int main(void) {
union foo x;
x.d = 3.3;
printf("%g\n", x.d);
union foo y = x; #1 whoops, declaration among expressions, not allowed in C89 printf("%g\n", y.d);
union foo z; #2 whoops, declaration among expressions, not allowed in C89 z = y;
printf("%g\n", z.d);
}
The above syntactic sugar could save a few characters of code if legal
since union members would not have to be explicitly mentioned in the code.


If you mean structure/union assignments, yes, they are valid in C89 and up.

From the C89 rationale:

3.3.2.3 Structure and union members

Since the language now permits structure parameters, structure assignment and
functions returning structures, the concept of a structure expression is now
part of the C language. A structure value can be produced by an assignment, by
a function call, by a comma operator expression or by a conditional operator
expression:

s1 = (s2 = s3)
sf(x)
(x, s1)
x ? s1 : s2

--
char*x(c,k,s)ch ar*k,*s;{if(!k) return*s-36?x(0,0,s+1):s ;if(s)if(*s)c=1 0+(c?(x(
c,k,0),x(c,k+=* s-c,s+1),*k):(x(* s,k,s+1),0));el se c=10;printf(&x( ~0,0,k)[c-~-
c+"1"[~c<-c]],c);}main(){x(0 ,"^[kXc6]dn_eaoh$%c","-34*1'.+(,03#;+, )/'///*");}
Nov 13 '05 #3
Pieter Droogendijk <gi*@binky.home unix.org> wrote in message:
If you mean structure/union assignments, yes, they are valid in C89 and up.

From the C89 rationale:

3.3.2.3 Structure and union members

Since the language now permits structure parameters, structure assignment and
functions returning structures, the concept of a structure expression is now
part of the C language. A structure value can be produced by an assignment,
by a function call, by a comma operator expression or by a conditional
operator expression:

s1 = (s2 = s3)
sf(x)
(x, s1)
x ? s1 : s2
But the above quote from 3.3.2.3 from the C89 rationale does not state whether
the same applies to unions (besides structures). Does it?

Furthermore, it does not mention the ins and outs of initializing a union at
declaration time rather than through an assignment, either via another union
variable or via an initializer list. Is this at all legal in C89? How about
in C99?

Jack Klein <ja*******@spam cop.net> wrote in message:
You can assign one union to another in C, this has been part of the
language since the original 1989 ANSI standard.
You claim this is true, but the above quote of the C89 rationale by Pieter
only talks about structures, not unions, so I am not entirely convinced.
And what if the union contains other structures and unions. Does assignment
of compatible unions still work in such cases, according to the C standard?
A union can contain only one member at a time, namely the one that was
last assigned to.
Any book that mentions unions states the above: that's what a union is.
If you assign that union to another union, that same member is still
valid in the new union and has the same value.
This is what I was hoping for, but does the standard even mention this?
What is there that you think is so unusual about unions that you would
not expect that code?


Besides the issue of

1. assignment of a union to a union

you have not addressed the issues of

2. union inizialization using a union variable on the RHS in C99

3. union initialization using a union initializer

I expect that these issues can be rather subtle, and they're not treated
very well in most textbooks since unions are considered a little out of
style, but they are nevertheless useful in many situations.

Best Regards,

Neil
Nov 13 '05 #4
On 17 Sep 2003 17:10:54 -0700, nz******@cs.mun .ca (Neil Zanella) wrote
in comp.lang.c:
Pieter Droogendijk <gi*@binky.home unix.org> wrote in message:
If you mean structure/union assignments, yes, they are valid in C89 and up.

From the C89 rationale:

3.3.2.3 Structure and union members

Since the language now permits structure parameters, structure assignment and
functions returning structures, the concept of a structure expression is now
part of the C language. A structure value can be produced by an assignment,
by a function call, by a comma operator expression or by a conditional
operator expression:

s1 = (s2 = s3)
sf(x)
(x, s1)
x ? s1 : s2
But the above quote from 3.3.2.3 from the C89 rationale does not state whether
the same applies to unions (besides structures). Does it?


The rationale is a very handy document indeed when one wants insight
on the reasons behind some of the design features of the C language,
but it is not normative. Have you looked at the C89 standard itself?
Furthermore, it does not mention the ins and outs of initializing a union at
declaration time rather than through an assignment, either via another union
variable or via an initializer list. Is this at all legal in C89? How about
in C99?

Jack Klein <ja*******@spam cop.net> wrote in message:
You can assign one union to another in C, this has been part of the
language since the original 1989 ANSI standard.
You claim this is true, but the above quote of the C89 rationale by Pieter
only talks about structures, not unions, so I am not entirely convinced.


It makes no difference what inference you choose to draw from the
rationale, or for that matter the exact wording of the rationale
itself. The rationale is not normative and is not the standard. The
standard is the standard, it is definitive and authoritative, barring
the inevitable human errors.

As for the ANSI89/ISO90 standard, the first paragraph of 6.2.2.1
states, in part, "A modifiable lvalue is an lvalue that does not have
array type, does not have an incomplete type, does not have a
const-qualified type. and if it is a structure or union. does not have
any member (including. recursively, any member of all contained
structures or unions) with a const-qualified type."

This specifically includes unions in the definition of modifiable
lvalues, and any modifiable lvalue can be assigned to with an rvalue
of appropriate type.

The very next sentence, the first sentence in the second paragraph,
states: "Except when it is the operand of the sizeof operator, the
unary & operator, the ++ operator, the -- operator, or the left
operand of the . operator or an assignment operator, an lvalue that
does not have array type is converted to the value stored in the
designated object (and is no longer an lvalue)."

So when you initialize a union with another union of compatible type,
or when you assign to a union from another union of compatible type,
the value of the source object is converted to an rvalue, and that
rvalue is stored in the destination object. This includes all
sub-objects ad infinitum.
And what if the union contains other structures and unions. Does assignment
of compatible unions still work in such cases, according to the C standard?
A union can contain only one member at a time, namely the one that was
last assigned to.
Any book that mentions unions states the above: that's what a union is.
If you assign that union to another union, that same member is still
valid in the new union and has the same value.


This is what I was hoping for, but does the standard even mention this?
What is there that you think is so unusual about unions that you would
not expect that code?


Besides the issue of

1. assignment of a union to a union

you have not addressed the issues of

2. union inizialization using a union variable on the RHS in C99


This is not a C99 issue. As I said in another post in another one of
your threads, there are certain differences between initialization and
assignment. One of the largest differences deals with non-modifiable
lvalues, meaning objects of array type or const qualified as above.
They may be initialized, not assigned. Another deals with static
storage duration modifiable lvalues at file scope, which can only be
initialized with compile-time constant expressions, but can be
assigned with different types of expressions by executing code.
3. union initialization using a union initializer

I expect that these issues can be rather subtle, and they're not treated
very well in most textbooks since unions are considered a little out of
style, but they are nevertheless useful in many situations.

Best Regards,

Neil


First, I don't have to address anything. I asserted something about
both the initialization and assignment of unions, and in almost 24
hours none of the other regulars has pounced on any error and ripped
me to shreds. I guarantee you this would have happened had I been
wrong.

What reason do you have to dispute my reply? You have no quote from
the standard that contradicts me, nor from any other poster to this
group.

Still, just this once, keeping to the C90 ISO standard...

=======
6.3.16 Assignment operators
[...]
Constraints
An assignment operator shall have a modifiable lvalue as its left
operand.
Semantics
An assignment operator stores a value in the object designated by the
left operand.
[...]
6.3.16.1 Simple assignment
Constraints
One of the following shall hold:
[...]
- the left operand has a qualified or unqualified version of a
structure or union type compatible with the type of the right;
========

So the ANSI89/ISO90 standard directly states that unions, as well as
structures, may be directly assigned.

========
6.57 Initialization
[...]
A brace-enclosed initializer for a union object initializes the member
that appears first in the declaration list of the union type.

The initializer for a structure or union object that has automatic
storage duration either shall be an initializer list as described
below, or shall be a single expression that has compatible
structure or union type. In the latter case. the initial value of the
object is that of the expression.
========

So the ANSI89/ISO90 standard directly and clearly states that a union
(with automatic storage duration) may be initialized from another
union of compatible type.

I leave it as an exercise to you to, since you seem to have a copy of
C99, either:

1. Find the corresponding wording in C99 to prove that both
assignment to and initialization of unions is still defined to be
exactly the same, other than the new designated initializers, or...

2. Some wording in C99 that changes this behavior.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Nov 13 '05 #5
Jack Klein wrote:
Have you looked at the C89 standard itself?


I downloaded a public last draft from Dan Pop once
but I lost the URL.
Somebody else, I think the name was Bobbits,
used to have a copy on the web, but it's not there anymore.

Do you know a URL for a C89 public last draft?

--
pete
Nov 13 '05 #6
pete wrote:
Jack Klein wrote:
Have you looked at the C89 standard itself?


I downloaded a public last draft from Dan Pop once
but I lost the URL.
Somebody else, I think the name was Bobbits,
used to have a copy on the web, but it's not there anymore.

Do you know a URL for a C89 public last draft?


http://danpop.home.cern.ch/danpop/ansi.c

Jirka

Nov 13 '05 #7

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

Similar topics

5
303
by: john sun | last post by:
Hi, I have a class with copy ctor and assignment operator. MyClasss obj1(data); MyClass obj2=obj1; in this case, the copy constructor is invoked instead of assignment operator. I cannot understand why? Thanks, John
8
6721
by: Josh Lessard | last post by:
Given a union definition: union problem_t { int mask; struct { int indices; int ops; } comp; };
50
3825
by: Charles Stapleton | last post by:
Given the folowing class class Ctest{ public: Ctest( int i, int j) :a(i) { b = j; } private: int a, b; } When creating an object of type Ctest, what advantage is there to setting
7
3733
by: skishorev | last post by:
What is the difference between copy initialization and assignment. How the memory will allocates the objects. Thanks &regards, Sai Kishore
8
3121
by: lovecreatesbea... | last post by:
K&R 2, sec 2.4 says: If the variable in question is not automatic, the initialization is done once only, conceptually before the program starts executing, ... . "Non-automatic variables are initialized before the program starts executing." -- What does this mean? What is the name of the stage in which the mentioned initialization is performed? Compile-time or run-time? In the following snippet, variables b and c are defined at line 7...
11
2439
by: asdf | last post by:
The oder of member initialization is the order in which the members are defined. So the following code is problematic: class X{ int i; int j; public: X(int val):j(val),i(j){}
26
1921
by: Old Wolf | last post by:
Ok, we've had two long and haphazard threads about unions recently, and I still don't feel any closer to certainty about what is permitted and what isn't. The other thread topics were "Real Life Unions" and "union {unsigned char u; ...} ". Here's a concrete example: #include <stdio.h> int main(void)
23
3661
by: Jess | last post by:
Hello, I understand the default-initialization happens if we don't initialize an object explicitly. I think for an object of a class type, the value is determined by the constructor, and for the built-in types, the value is usually garbage. Is this right? However, I'm a bit confused about value-initialization, when does it happen, and what kind of values are assigned to objects?
2
2381
by: timlyee | last post by:
int *p = new int; auto_ptr<intap1 = p; //will fail on 3 1 auto_ptr<intap1(p); //ok 2 *ap1 = 12; // 3 the first situation has called : explicit auto_ptr(_Ty *_Ptr = 0) _THROW0() the second : auto_ptr(auto_ptr_ref<_Ty_Right) _THROW0()
0
9537
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
9319
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
9243
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...
0
8241
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6795
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
6073
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
4599
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...
0
4869
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2213
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.