473,769 Members | 3,840 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Colon (:) syntax in defining fields in a struct

Hello all,

I recently came across the following segment of code that defines a C
struct:

typedef struct
{
unsigned char unused_bits:4;
unsigned char wchair_state:2;
} xyz;

What do the numbers 4 and 2 refer to?

If I define a second struct as below:

typedef struct
{
unsigned char unused_bits;
unsigned char wchair_state;
} abc;
and then declare

void main(void)
{
xyz _xyz;
abc _abc;
}

In terms of memory allocation, is there any difference between that
allocated for _xyz and _abc?

Any feedback would be much appreciated.

Thanks
Raj
Nov 14 '05
16 12057
# Ok, you've got me! Why is the above modification necessary and why
# could the original invoke undefined behavior?

Because there's a clique running about that gets so angry that I answer
questions they doomed unanswerable, that they have to attack me in anyway
possible.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
She broke your heart and inadvertendentl y drove men to deviant lifestyles.
Nov 14 '05 #11
"Fao, Sean" wrote:

Fao, Sean wrote:
Peter Shaggy Haywood wrote:
>># In terms of memory allocation, is there any difference between that

# allocated for _xyz and _abc?

Add
printf("%d %d\n",sizeof(xy z),sizeof(abc)) ;
I would expect to see it print
1 2

I would expect the unexpected. When you invoke the wrath of the
undefined behaviour gods, you never really know what to expect. Well,
sometimes you can make a reasonable guess, but it can always go wrong
and do something you least expect.
Instead, try this:

printf("sizeof xyz = %lu, sizeof abc = %lu\n",
(unsigned long)sizeof xyz,
(unsigned long)sizeof abc);

Ok, you've got me! Why is the above modification necessary and why
could the original invoke undefined behavior?


Actually, let me see if I can figure this out for myself.

The sizeof operator results in something of type size_t, which I assume
on some implementations *could* be an unsigned long. If that's correct,
why not unsigned long long?

But this doesn't answer my question as to where the UD could come into
play. Obviously, the original code with a %d could not display any
number over INT_MAX; however, the result would still be defined (at
least I _think_ rolling over is defined)

Am I missing something?


Yes. How does the calling code know to transform a size_t into an
int? This is a variadic function being called. Lets say an int
occupies two bytes, and a size_t occupies 4 bytes, and we a using
a stack machine. The printf operates on two 2 byte portions of
the first (or last) parameter. Maybe those are trap values. UB
everywhere you look.

--
A: Because it fouls the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 14 '05 #12
"Fao, Sean" <en**********@y ahoo.comI-WANT-NO-SPAM> writes:
Fao, Sean wrote:
Peter Shaggy Haywood wrote:
>># In terms of memory allocation, is there any difference between that

# allocated for _xyz and _abc?

Add
printf("%d %d\n",sizeof(xy z),sizeof(abc)) ;
I would expect to see it print
1 2

I would expect the unexpected. When you invoke the wrath of the
undefined behaviour gods, you never really know what to expect. Well,
sometimes you can make a reasonable guess, but it can always go wrong
and do something you least expect.
Instead, try this:

printf("sizeof xyz = %lu, sizeof abc = %lu\n",
(unsigned long)sizeof xyz,
(unsigned long)sizeof abc);

Ok, you've got me! Why is the above modification necessary and why
could the original invoke undefined behavior?


Actually, let me see if I can figure this out for myself.

The sizeof operator results in something of type size_t, which I assume
on some implementations *could* be an unsigned long. If that's correct,
why not unsigned long long?

But this doesn't answer my question as to where the UD could come into
play. Obviously, the original code with a %d could not display any
number over INT_MAX; however, the result would still be defined (at
least I _think_ rolling over is defined)

Am I missing something?


Yes, you're missing the fact that printf() has no way of knowing the
actual types of its arguments other than the format string.

Let's take a simple example:

#include <stdio.h>
int main(void)
{
long int n = 42;
printf("n = %d\n", n);
return 0;
}

By using "%d" in the format string, you're promising that the
corresponding argument is going to be of type int. The compiler can't
check that you've kept your promise; the format string could be a
variable, so the compiler has no way of knowing what's in it.
(Actually, some compilers can and do perform such checks if the format
is a literal, but the standard doesn't require it. "gcc -Wall" prints
a warning for mismatched printf formats.) The long int value is not
converted it int; you've told the compiler to assume that it's
*already* of type int. In other words, you've lied to the compiler,
and it will get its revenge.

What actually happens is going to depend on a number of things, such
as the parameter-passing convention. One possibility is that the
caller will push a long int (the value of n) onto the stack, and
printf() will pop an int from the stack, because you told it to expect
an int. In many cases, this will happen to work (because int and long
int are the same size, or because an int argument is passed the same
way as a long int argument, or because you just got lucky.) In other
cases, it could corrupt the stack pointer, causing subsequent code to
lose track of which local variables are stored where (this is unlikely
for historical reasons, but the standard allows it). The bottom line
is that it's undefined behavior, meaning that the standard places no
constraints on what could happen, from behaving as you expect to
making demons fly out your nose. (Behaving as you expect is actually
the worst outcome, since it prevents you from finding the error until
you port the code to another platform, and it fails subtly or
spectactularly at the most inconvenient possible moment.)

By contrast, consider this example:

#include <stdio.h>

static void print_int(int x)
{
printf("%d", x);
}

int main(void)
{
long int n = 42;
printf("n = ");
print_int(n);
printf("\n");
return 0;
}

This doesn't invoke undefined behavior; it's guaranteed to print

n = 42

(assuming there are no problems writing to stdout). The function
print_int() expects an argument of type int, but you're passing it an
argument of type long int, so the argument is implicitly converted
from long int to int before being passed. Since the value 42 is
guaranteed to fit into an int, overflow is not an issue.

So why is the implicit conversion performed on the call to print_int()
but not on the call to printf()? Because for print_int(), there's a
prototype that tells the compiler that it expects an argument of type
int. The compiler knows it's going to need to generate an implicit
conversion, and the standard requires it to do so. For printf(),
there's also a prototype (assuming you've remembered the
"#include <stdio.h>"; if not, any call to printf() invokes undefined
behavior) -- but the prototype looks like this:

int printf(const char * restrict format, ...);

(The "restrict" keyword was added in C99; don't worry about the
"const" or "restrict" keywords for now.) The point is that the
compiler, given this prototype, has no way of knowing that the second
argument in printf("%d", x) is supposed to be an int.

Getting back to the original example:

printf("%d %d\n",sizeof(xy z),sizeof(abc)) ;

Given the format string, printf() assumes (because you promised it)
that the second and third arguments are going to be of type int. The
compiler doens't know about this promise, so it passes arguments of
type size_t. Undefined behavior.

One solution is to use *explicit* conversions, so you know that you're
passing arguments of the right type:

printf("%d %d\n", (int)sizeof(xyz ), (int)sizeof(abc ));

If you happen to know that sizeof(xyz) and sizeof(abc) will both fit
into an int, this is fine. If not, use a bigger type (probably an
unsigned one, since size_t is unsigned):

printf("%lu %lu\n",
(unsigned long)sizeof(xyz ),
(unsigned long)sizeof(abc ));

Or, if you happen to have a C99-compliant implementation, you can use
the new 'z' length modifier, which specifically applies to size_t
arguments:

printf("%zu %zu\n", sizeof(xyz), sizeof(abc));

but that gives you undefined behavior in a C90 implementation.

--
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 #13
SM Ryan <wy*****@tang o-sierra-oscar-foxtrot-tango.fake.org> writes:
# Ok, you've got me! Why is the above modification necessary and why
# could the original invoke undefined behavior?

Because there's a clique running about that gets so angry that I answer
questions they doomed unanswerable, that they have to attack me in anyway
possible.


Nope.

The modification in question was changing
printf("%d %d\n",sizeof(xy z),sizeof(abc)) ;
to
printf("sizeof xyz = %lu, sizeof abc = %lu\n",
(unsigned long)sizeof xyz,
(unsigned long)sizeof abc);

The former will happen to work on many systems, but it invokes
undefined behavior, for reasons I've explained at length elswhere in
this thread. The latter corrects the problem.

If someone corrects a technical error I've made, I consider it a
favor, not an attack. Similarly, if someone pointed out to me that my
quoting style and signature delimiter were causing real problems for
other readers and posters, I would try to correct the problem; you
have stubbornly refused to do so, for no reason that you've ever made
clear.

--
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 #14
In article <10************ *@corp.supernew s.com>, wyrmwif@tango-sierra-oscar-
foxtrot-tango.fake.org says...
... there's a clique running about that gets so angry that I answer
questions they doomed unanswerable, that they have to attack me in anyway
possible.
I haven't seen anyone attack you, although I admit that people are often
miffed to find out they got something "not quite right" and a bunch of
folks jumped on them here. That's one of the less fortunate side-effects
of this being an incredibly good place to get information on C, because
of this. The point is that the "pedants" pretty much guarantee as a
collective that no mistake will go unpunished. It's sort of the "Borg"
of virtual proofreaders. Don't make the mistake of thinking that having
such horsepower applied to your posts is a bad thing, consider it rather
to be a learning (trial by fire) experience unequalled elsewhere and
move on to better programming.
--
SM Ryan http://www.rawbw.com/~wyrmwif/
She broke your heart and inadvertendentl y drove men to deviant lifestyles.


I note that my newsreader didn't strip your signature automatically. The
reason is that you do not have the customary ' ' character after the '--'
in your sig. It's quite simple to fix. Here's a free example:

--
Randy Howard
To reply, remove FOOBAR.
Nov 14 '05 #15
Randy Howard wrote:
.... snip ...
--
SM Ryan http://www.rawbw.com/~wyrmwif/
She broke your heart and inadvertendentl y drove men to deviant lifestyles.


I note that my newsreader didn't strip your signature automatically. The
reason is that you do not have the customary ' ' character after the '--'
in your sig. It's quite simple to fix. Here's a free example:


He doesn't care. He also insists on his deviant quote marker. So
the only useful correction is PLONKing.

--
Some similarities between GWB and Mussolini:
a) The strut; b) Making war until brought up short:
Mussolini: Ethiopia, France, Greece.
GWB: Afghanistan, Iraq.
Nov 14 '05 #16
CBFalconer <cb********@yah oo.com> writes:
Randy Howard wrote:

... snip ...
--
SM Ryan http://www.rawbw.com/~wyrmwif/
She broke your heart and inadvertendentl y drove men to deviant lifestyles.


I note that my newsreader didn't strip your signature automatically. The
reason is that you do not have the customary ' ' character after the '--'
in your sig. It's quite simple to fix. Here's a free example:


He doesn't care. He also insists on his deviant quote marker. So
the only useful correction is PLONKing.


I seldom bother replying to him, but it is sometimes useful to correct
misinformation for the benefit of others. (That's not to imply that
he's always wrong; he isn't.)

--
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 #17

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

Similar topics

8
1591
by: wesley | last post by:
Hi, What's the reasoning of having struct in .Net? Since they hardly differ with classes? Are there any advantages using struct instead of classes? Thanks
3
4615
by: Bob Hairgrove | last post by:
Surely this is a no-brainer, but sometimes I think I must have no brain (no comments, please<g>). Anyway, I have the following struct containing bit fields: struct ExtPenStyle { unsigned long style : 4; unsigned long : 4; // unused unsigned long endcap : 2; unsigned long : 2; // unused
2
2953
by: Simon Elliott | last post by:
I have some legacy code which initialises an array using C syntax like this: struct bar { int i1_; int i2_; bool b1_; };
5
3831
by: Sönke Tesch | last post by:
Hi everybody, I have a problem with the following piece of code: 141: /* A data block to manage a single log target: */ 142: typedef struct { 143: apr_reslist_t *dbs; /* connection pool */ 144: 145: const char *uri; /* the complete log uri.. */
2
5056
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 ?
4
2373
by: Leo | last post by:
Hello, I have a C dll with a method signature of: int activate(datastruct *data) where datastruct is defined as: typedef struct datastruct { long result;
1
10518
by: Svenn Are Bjerkem | last post by:
Hi Forum, I am not very much experienced with c++, but I have unfortunately programmed a lot of c and have a problem understanding the purpose of defining a struct in the private part of a class. I am looking at the example code for Interviews in the Qt-4 example code, which unfortunately hasn't been documented yet. http://doc.trolltech.com/4.2/demos-interview.html
10
2581
by: Mosfet | last post by:
Hi, I would like more info about deriving from an existing C struct. Let's say I am fed up with always writing the same code shown below : MYSTRUCT foo; memset( &foo, 0, sizeof(MYSTRUCT) ); foo.cbSize = sizeof(MYSTRUCT);
4
1279
by: stupot1987 | last post by:
hey im new to this site but found it has helped me in the past with other similar problems. i want to be able to compare 2 fields in my sql my code is as follows: Private Sub Command1_Click() Exit Sub Adodc1.RecordSource = "SELECT Stock., Stock.Description, Stock., Stock. FROM Stock; WHERE Stock.) < Stock.;" Adodc1.Recordset.Requery Adodc1.Refresh DataGrid1.Refresh
0
9579
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
9422
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
10206
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...
0
10035
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
8863
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...
0
5293
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
3949
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
3556
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2811
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.