473,725 Members | 2,127 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Union nested in structure.

I created a C file say struct.c with the following structure
declarations in the same file

struct A
{
union key
{
int i;
float f;
}k1;
};
struct B
{
union key
{
int i;
float f;
}k2;
};
When I compiled this code using
gcc -c struct.c

I got a error

"redefiniti on of `union key'" at the definition of "union key" in
struct B.
Is it not that the scope "union key" defined in struct A is limited to
struct A? From the behaviour it looks like that nested unions have
global scope.

Can anyone provide me the reason for such behavior?

When i made the file as struct.cpp it compiled without any problem.
Similar is the behaviour if I nest a struct inside a struct..

Nov 14 '05 #1
10 11380

ta*****@gmail.c om wrote:
I created a C file say struct.c with the following structure
declarations in the same file

struct A
{
union key
{
int i;
float f;
}k1;
};
struct B
{
union key
{
int i;
float f;
}k2;
};
When I compiled this code using
gcc -c struct.c

I got a error

"redefiniti on of `union key'" at the definition of "union key" in
struct B.
Is it not that the scope "union key" defined in struct A is limited to
struct A? From the behaviour it looks like that nested unions have
global scope.

Can anyone provide me the reason for such behavior?

When i made the file as struct.cpp it compiled without any problem.
Congratulations : You have just found one of the differences between
the two languages C and C++.
C has _one_ namespace for _all_ structure, union and enumeration tags.
No scope. Effectively, you can write:
struct A
{
union key
{
int i;
float f;
}k1;
};

struct B
{
union key k2;
};
or
union key
{
int i;
float f;
};

struct A
{
union key k1;
};

struct B
{
union key k2;
};
Cheers
Michael

Similar is the behaviour if I nest a struct inside a struct..


Exactly as the language standard demands it.
Cheers
Michael
--
E-Mail: Mine is a gmx dot de address.

Nov 14 '05 #2
But why does C standard demand such a behaviour? C is very particular
about scope. Why is that scope rules are not followed in case of
structures, unions and enums?

Nov 14 '05 #3
Tapeesh wrote:

But why does C standard demand such a behaviour? C is very particular
about scope. Why is that scope rules are not followed in case of
structures, unions and enums?


Your question makes no sense. What behaviour? In usenet so called
previous articles are often not available at the receivers station,
so each article should stand on its own. That is why we include
attributions and quotations. Even with googles broken beta system
you can do it, see my sig below.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #4
"Tapeesh" <ta*****@gmail. com> writes:
But why does C standard demand such a behaviour? C is very particular
about scope. Why is that scope rules are not followed in case of
structures, unions and enums?


The scope rules are followed. It just happens that the rules are
different for struct, union, and enum tags.

As for why it was originally defined that way, I suppose it was just
easier. This probably goes back at least 30 years. You can certainly
argue that limiting the scope of a tag makes more sense (and
apparently Stroustrup felt strongly enough about it to change the rule
for C++), but the C rules rarely cause problem in practice. (Your
code is one of the rare cases.) It can't be changed now without
potentially breaking existing code.

(BTW, this is a good argument against always compiling your C code
with a C++ compiler; it can cause you to miss this kind of error.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #5

In article <11************ **********@f14g 2000cwb.googleg roups.com>, "Tapeesh" <ta*****@gmail. com> writes:

I see Chuck Falconer has already posted explaining why you should
(properly) quote text you are replying to, and how to do so correctly
with the braindead Google Groups interface. I won't repeat those
instructions, but I urge you to take them to heart.
But why does C standard demand such a behaviour?
Because that's how the committee thought it should work, and not
specifying the tag scope rules would have been a Bad Thing.

(And, IIRC, the single global-scope tag namespace existed in pre-
standard C as well, so they're preserving existing practice. What
did change was the separation of members into their own scoped
namespace. Or was it that members had their own namespace, but it
had global scope? Or was there only a single namespace for tags,
members, and ordinary identifiers? I no longer have a pre-standard
K&R to consult.)
C is very particular about scope.
With good reason. That does not mean, however, that the scoping
rules are or should be the same for all namespaces.
Why is that scope rules are not followed in case of
structures, unions and enums?


They are. They're just different for the tag namespaces.

The only reason to put a tag on a struct (or union) is to make it a
distinct type. You can leave the tags off structs (or unions) if
they don't need to be treated as distinct types. Often that's the
case when you're defining one struct inside another; otherwise, why
not define the inner one separately, first, to show that it may be
used on its own?

--
Michael Wojcik mi************@ microfocus.com

It does basically make you look fat and naked - but you see all this stuff.
-- Susan Hallowell, TSA Security Lab Director, on "backscatte r" scanners
Nov 14 '05 #6
>
(BTW, this is a good argument against always compiling your C code
with a C++ compiler; it can cause you to miss this kind of error.)


Well considering 99.9998% of C/C++ compilers will compile aprogram.c
as a 'C' language file, I don't see this problem popping up often, unless
of course they are using command-line parameters (and you'd have a hard
time finding them with gcc [joking]).

Nathaniel L. Walker
Nov 14 '05 #7
"Nathaniel L. Walker" <NatLWalker@no_ email.org> writes:
(BTW, this is a good argument against always compiling your C code
with a C++ compiler; it can cause you to miss this kind of error.)


Well considering 99.9998% of C/C++ compilers will compile aprogram.c
as a 'C' language file, I don't see this problem popping up often,
unless of course they are using command-line parameters (and you'd
have a hard time finding them with gcc [joking]).


This problem pops up all the time here. A lot of people name their C
source files with a ".cpp" suffix. (Note also that some OSs don't
distinguish between "aprogram.c " and "aprogram.C "; I'm not sure how
compilers on those systems behave.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #8
Nathaniel L. Walker wrote:
(BTW, this is a good argument against always compiling your C code
with a C++ compiler; it can cause you to miss this kind of error.)
Well considering 99.9998% of C/C++ compilers will compile aprogram.c


GNU cc and c++ aren't in that list. See example below.
as a 'C' language file, I don't see this problem popping up often, unless
of course they are using command-line parameters (and you'd have a hard
time finding them with gcc [joking]).

Nathaniel L. Walker


/* trouble.c
(5 green apples + 4 red apples) != 9 red apples.
C != C++.
*/
#include <stdio.h>

enum truth_value {lies, truth};

int
main (void)
{
const enum truth_value statistics = lies;

char *delete = "telling the C++ compiler to throw up.";

if (statistics == lies)
printf ("you know what I mean. :)\n");

puts (delete);

return 0;
}

----
Compiling with a C compiler (one of the most popular ones):

% gcc -pedantic -Wall -std=c89 -o statistics statistics.c
or
% gcc -pedantic -Wall -std=c99 -o statistics statistics.c
% ./statistics
you know what I mean. :)
telling the C++ compiler to throw up.

Compiling with a C++ compiler (one of the most popular ones, again):

% g++ -pedantic -Wall -o statistics statistics.c
statistics.c: In function `int main()':
statistics.c:10 : error: expected primary-expression before "char"
statistics.c:10 : error: expected `;' before "char"
statistics.c:15 : error: expected primary-expression before ')' token

Ooh, my C++ compiler doesn't recognize the .c extension that is so
very clearly present right there.

Bottom line: C != C++. Use a C compiler to compile C code and
use a C++ compiler to compile C++ code. :)

Regards,
Jonathan.

--
Email: "jonathan [period] burd [commercial-at] gmail [period] com" sans-WSP

"I usually swear at C++, but so far it has never sworn back."
- Ben "Noir"
Nov 14 '05 #9
Jonathan Burd wrote:
Nathaniel L. Walker wrote:

<snip>

/* trouble.c
Should be statistics.c.
Regards,
Jonathan.

--
Email: "jonathan [period] burd [commercial-at] gmail [period] com" sans-WSP

"I usually swear at C++, but so far it has never sworn back."
- Ben "Noir"
Nov 14 '05 #10

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

Similar topics

2
2162
by: d2r2 | last post by:
Hi, I'm trying to run a nested (UNION) query against a MSAccessXP database (version 2002; build 10.6501.6714; SP3) In Access the SQL-statement executes just fine. When I run it in a asp-page I get the following error: Microsoft JET Database Engine (0x80040E10) No value given for one or more required parameters. Can a nested union-query be used at all or should I use an intermediate
3
2243
by: Ann Huxtable | last post by:
Hi, I am writing a nested table structure to mimic data returned from a database (actually, a heirarchical recordset). I am representing the cells where the actual data is stored, by a union: class Cell { union { char* s ; //std::string s ;
6
3331
by: Neil Zanella | last post by:
Hello, I would like to know what the C standards (and in particular the C99 standard) have to say about union initializers with regards to the following code snippet (which compiles fine under gcc 3.2.2 but does not produce the expected results, the expected results being the ones annotated in the comments in the code): #include <stdlib.h>
2
5054
by: Peter Dunker | last post by:
Hi, I will write ANSI C89. Is the following struct defenition correct ? I wrote it with VC6(Windows IDE) and at first no Problem. As I changed a compiler switch to 'no language extension', the compiler said that the union has no name. Is it right that in ANSI C the union must be named inside this kind of structure ?
67
10734
by: S.Tobias | last post by:
I would like to check if I understand the following excerpt correctly: 6.2.5#26 (Types): All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Does it mean that *all* structure (or union) types have the same alignment? Eg. type
18
2375
by: ranjeet.gupta | last post by:
Dear ALL As we know that when we declare the union then we have the size of the union which is the size of the highest data type as in the below case the size should be 4 (For my case and compiler), and it is, what I conclude from the below code union data_type {
5
1689
by: Mike | last post by:
Within the following structure, TopStruct, I'd like to create 3 other structures, 2 of which make up a union. The first structure will always contain some data that I need and should never be overwritten, i.e. should not be part of the union. The remaining 2, UnionData1 and UnionData2, make up the union and are populated as needed. I want to be certain that this code will work as planned. Specifically, if the field offsets of the...
18
12954
by: Mockey Chen | last post by:
My friend ask me a question as following: give a union SU define as: typedef union _SU { short x; struct y{ char a; short b; char c;
4
10538
by: benn686 | last post by:
I have a structure that contains a union that Id like to initialize at compile time... something like: //global declare and initialize fullStructType var1 = { unionMember.union1.field1 = 100; unionMember.union1.field2 = 200 }; fullStructType var2 = { { unionMember.union2 = 300 } , { unionMember.union2 = 400 } };
0
8752
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9257
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...
0
9113
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
8097
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
6702
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
6011
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
4519
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
3221
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
3
2157
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.