473,321 Members | 1,748 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,321 software developers and data experts.

Question about warning

When I compile this (with GCC and optimizations on):

void foo(void)
{
int a;
float f = *((float *) &a);
}

I get the warning : "dereferencing type-punned pointer will break
strict-aliasing rules". Does this mean that f and a can be stored in the
same memory location?
--
Daniel Sjöblom
Remove _NOSPAM to reply by mail
Nov 14 '05 #1
12 1416

"Daniel Sjöblom" <ds******@mbnet.fi_NOSPAM> wrote

When I compile this (with GCC and optimizations on):

void foo(void)
{
int a;
float f = *((float *) &a);
}

I get the warning : "dereferencing type-punned pointer will break
strict-aliasing rules". Does this mean that f and a can be stored in the
same memory location?

No. A compiler is allowed to warn about anything it likes (so a
sophisticated compiler could warn about British spelling in a function
called setcolour(), for example).
Your function is fairly useless in well-designed code, because a bitwise
reinterpretation of an integer as a float is non-portable, not human
meaningful, and not something you should need to do (though in practise you
might need to do it, for instance to speed up the floating point operations
by twiddling bits directly). So the compiler warns about it.
Nov 14 '05 #2
On Sun, 27 Jun 2004 19:23:46 +0300, Daniel Sjöblom
<ds******@mbnet.fi_NOSPAM> wrote in comp.lang.c:
When I compile this (with GCC and optimizations on):

void foo(void)
{
int a;
float f = *((float *) &a);
}

I get the warning : "dereferencing type-punned pointer will break
strict-aliasing rules". Does this mean that f and a can be stored in the
same memory location?


It means that this code produces undefined behavior. You have broken
the rules, and the C standard no longer places any requirements on the
result. Anything that happens when this code is executed, or even
compiled, is beyond the scope of the C language.

--
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.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #3
Hello!
I dont know what u want to achive with the code but my guess would be that
u want to cast whatever value 'a' has to
'f'. (converting int to float)
Like
---------------
void foo(void)
{
int a;
float f = (float)a;
}
---------------
However the compiler will warn for use of an uninitzialized use of 'a'
//Jörgen Tapani
"Daniel Sjöblom" <ds******@mbnet.fi_NOSPAM> skrev i meddelandet
news:40**********************@news.mbnet.fi...
When I compile this (with GCC and optimizations on):

void foo(void)
{
int a;
float f = *((float *) &a);
}

I get the warning : "dereferencing type-punned pointer will break
strict-aliasing rules". Does this mean that f and a can be stored in the
same memory location?
--
Daniel Sjöblom
Remove _NOSPAM to reply by mail

Nov 14 '05 #4
>"Daniel Sjöblom" <ds******@mbnet.fi_NOSPAM> wrote
When I compile this (with GCC and optimizations on):

void foo(void)
{
int a;
float f = *((float *) &a);
}

I get the warning : "dereferencing type-punned pointer will break
strict-aliasing rules". Does this mean that f and a can be stored in the
same memory location?

In article <cb**********@newsg1.svr.pol.co.uk>
Malcolm <ma*****@55bank.freeserve.co.uk> writes:No. A compiler is allowed to warn about anything it likes (so a
sophisticated compiler could warn about British spelling in a function
called setcolour(), for example).
True, but irrelevant in this case.
Your function is fairly useless in well-designed code, because a bitwise
reinterpretation of an integer as a float is non-portable ...
More importantly, in future versions of gcc (and perhaps even current
versions on certain machines), the code above will not even achieve
its intent:
... not something you should need to do (though in practise you
might need to do it, for instance to speed up the floating point operations
by twiddling bits directly). So the compiler warns about it.


In particular, the "bit twiddling" via sharing of underlying storage
simply WILL NOT HAPPEN (under some circumstances), because the C
standards say the compiler is allowed to assume that it DOES not
happen. In order to "bit-twiddle" a float in C, you need to use
a character type -- "unsigned char" is best -- to access its
individual bytes.

The exact circumstances under which gcc will (or might) optimize
away the desired bit-twiddling are hard to describe, but the C
standards always allow it, hence the warning.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #5

"Chris Torek" <no****@torek.net> wrote in message
In particular, the "bit twiddling" via sharing of underlying storage
simply WILL NOT HAPPEN (under some circumstances), because the > C standards say the compiler is allowed to assume that it DOES not happen. In order to "bit-twiddle" a float in C, you need to use
a character type -- "unsigned char" is best -- to access its
individual bytes.

So

int samesign(float x, float y)
{
return ((*(int *)&x ^ *(int *)&y) & SIGNBIT) ? 0 : 1;
}

is not OK (SIGNBIT is a constant with the float sign set)

int samesign(float x, float y)
{
return (*((unsigned char *)&x +1)^ *((unsigned char*)&y + 1) & SIGNBIT_CH
? 0 : 1;
}

is OK, assuming a bit unrealistically that the sign is in the second byte of
the float.
Nov 14 '05 #6
On Mon, 28 Jun 2004 00:31:34 +0100, "Malcolm"
<ma*****@55bank.freeserve.co.uk> wrote in comp.lang.c:

"Chris Torek" <no****@torek.net> wrote in message
In particular, the "bit twiddling" via sharing of underlying storage
simply WILL NOT HAPPEN (under some circumstances), because the > C

standards say the compiler is allowed to assume that it DOES not
happen. In order to "bit-twiddle" a float in C, you need to use
a character type -- "unsigned char" is best -- to access its
individual bytes.

So

int samesign(float x, float y)
{
return ((*(int *)&x ^ *(int *)&y) & SIGNBIT) ? 0 : 1;
}

is not OK (SIGNBIT is a constant with the float sign set)

int samesign(float x, float y)
{
return (*((unsigned char *)&x +1)^ *((unsigned char*)&y + 1) & SIGNBIT_CH
? 0 : 1;
}

is OK, assuming a bit unrealistically that the sign is in the second byte of
the float.


It is in the sense that it is not undefined behavior. Any area of
memory that your program has the right to read may be read as an array
of unsigned chars. They are unique in C in that they have no trap or
error representations, every possible combination of bits represents a
valid value.

Whether it is wise to do this is another story. Assuming it works on
a particular implementation, it is hideously non-portable to other
implementations.

--
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.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #7
On Sun, 27 Jun 2004 19:23:46 +0300, Daniel Sjöblom
<ds******@mbnet.fi_NOSPAM> wrote:
When I compile this (with GCC and optimizations on):

void foo(void)
{
int a;
float f = *((float *) &a);
}

I get the warning : "dereferencing type-punned pointer will break
strict-aliasing rules". Does this mean that f and a can be stored in the
same memory location?


What your compiler is trying to tell you is that if you use the
address of a as the address of a floating point variable, it is
possible that

You will have an alignment problem which will prevent the code
from working. It is possible that a properly aligned int does not
satisfy the alignment for a float.

You will have a value problem when you dereference the address
which will prevent the code from working. It is possible that the bit
pattern in the int is not a valid bit pattern for a float. (Your
current code has undefined behavior anyway since a is not initialized
but you attempt to evaluate it. The situation described applies if a
is initialized.)
<<Remove the del for email>>
Nov 14 '05 #8
Chris Torek wrote:
In article <cb**********@newsg1.svr.pol.co.uk>
Malcolm <ma*****@55bank.freeserve.co.uk> writes:
More importantly, in future versions of gcc (and perhaps even current
versions on certain machines), the code above will not even achieve
its intent:

... not something you should need to do (though in practise you
might need to do it, for instance to speed up the floating point operations
by twiddling bits directly). So the compiler warns about it.

In particular, the "bit twiddling" via sharing of underlying storage
simply WILL NOT HAPPEN (under some circumstances), because the C
standards say the compiler is allowed to assume that it DOES not
happen. In order to "bit-twiddle" a float in C, you need to use
a character type -- "unsigned char" is best -- to access its
individual bytes.

The exact circumstances under which gcc will (or might) optimize
away the desired bit-twiddling are hard to describe, but the C
standards always allow it, hence the warning.


I knew that dereferencing a cast pointer can cause traps if the address
is not properly aligned for the cast to type. But are you saying that
the compiler can reorder the instructions so that the bits of the float
can be just about any value the int has at some point (assuming no
alignment problems)? Does this also mean that the compiler cannot safely
reorder stores/loads to/from any char pointer?

Thanks to everyone who responded.
--
Daniel Sjöblom
Remove _NOSPAM to reply by mail
Nov 14 '05 #9
In <ea********************************@4ax.com> Jack Klein <ja*******@spamcop.net> writes:
Whether it is wise to do this is another story. Assuming it works on
a particular implementation, it is hideously non-portable to other
implementations.


OTOH, if one resorts to such a thing, it is because the portable version
is hideously slow on that implementation and the performance difference
does matter to the overall program performance.

Real life programming constraints are more complex than "portable code:
good, non-portable code: bad".

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #10
In <40**********************@news.mbnet.fi> =?ISO-8859-1?Q?Daniel_Sj=F6blom?= <ds******@mbnet.fi_NOSPAM> writes:
When I compile this (with GCC and optimizations on):

void foo(void)
{
int a;
float f = *((float *) &a);
}

I get the warning : "dereferencing type-punned pointer will break
strict-aliasing rules". Does this mean that f and a can be stored in the
same memory location?


Nope, it means that you're trying to access a memory area using another
type than the one used in the declaration of the object occupying that
area. Sometimes, this is allowed, but in the general case this results
in undefined behaviour. Here's the exact text of the standard:

7 An object shall have its stored value accessed only by an lvalue
expression that has one of the following types:73)

- a type compatible with the effective type of the object,

- a qualified version of a type compatible with the effective
type of the object,

- a type that is the signed or unsigned type corresponding to
the effective type of the object,

- a type that is the signed or unsigned type corresponding to
a qualified version of the effective type of the object,

- an aggregate or union type that includes one of the
aforementioned types among its members (including, recursively,
a member of a subaggregate or contained union), or

- a character type.
____________________

73) The intent of this list is to specify those circumstances
in which an object may or may not be aliased.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #11
On 28 Jun 2004 14:27:05 GMT, Da*****@cern.ch (Dan Pop) wrote in
comp.lang.c:
In <ea********************************@4ax.com> Jack Klein <ja*******@spamcop.net> writes:
Whether it is wise to do this is another story. Assuming it works on
a particular implementation, it is hideously non-portable to other
implementations.


OTOH, if one resorts to such a thing, it is because the portable version
is hideously slow on that implementation and the performance difference
does matter to the overall program performance.

Real life programming constraints are more complex than "portable code:
good, non-portable code: bad".

Dan


You do seem to have a problem reading the actual words that I write
before you respond to them.

Where in my original post did I say that non-portable code was bad?

In fact where did I imply any judgment at all?

How do you read this sentence "Whether it is wise to do this is
another story." as implying that it is or is not wise? It prefaces a
warning about the portability issue, nothing more.

--
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.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #12
In <j7********************************@4ax.com> Jack Klein <ja*******@spamcop.net> writes:
On 28 Jun 2004 14:27:05 GMT, Da*****@cern.ch (Dan Pop) wrote in
comp.lang.c:
In <ea********************************@4ax.com> Jack Klein <ja*******@spamcop.net> writes:
>Whether it is wise to do this is another story. Assuming it works on
>a particular implementation, it is hideously non-portable to other
>implementations.
OTOH, if one resorts to such a thing, it is because the portable version
is hideously slow on that implementation and the performance difference
does matter to the overall program performance.

Real life programming constraints are more complex than "portable code:
good, non-portable code: bad".

Dan


You do seem to have a problem reading the actual words that I write
before you respond to them.


Relax, no such problems.
Where in my original post did I say that non-portable code was bad?

In fact where did I imply any judgment at all?

How do you read this sentence "Whether it is wise to do this is
another story." as implying that it is or is not wise? It prefaces a
warning about the portability issue, nothing more.


A useless warning about the portability issue, because its author pointed
it out himself:

is OK, assuming a bit unrealistically that the sign is in the second
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
byte of the float.

So, assuming *you* can read the text you're commenting upon, what was the
point of your own comments? Everyone, *including the author*, knew, that
the example was non portable and that it served a completely different
purpose: to verify if its author got the aliasing rules right.

Therefore, your comments could be *meaningfully* interpreted *only* in a
pejorative key.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #13

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

Similar topics

4
by: Hans | last post by:
Hello group, I have a table with the next contents. It lists data about : Who sent what kind of message at what time. For the Level column: The highest level is Critical, the middle is Warning,...
0
by: scorpion | last post by:
This question is more XML Security (and specifically, on the Apache XML security implementation). When I sign or open signed XML document, I see the following warning: .... WARNING: Found an...
3
by: Bryan Parkoff | last post by:
I tell C++ Compiler to use level 4 warning instead of level 3 warning so all variables can be calculated accuracy with no prone error. It will give you a warning like this. unsigned short A =...
4
by: howarddevore2003 | last post by:
hi when i try to compile this: #include <iostream.h> int main() { int i; cout << "Please enter an integer value: "; cin >> i; cout << "the value you entered is " << i;
2
by: Rouben Rostamian | last post by:
The main() function in the following code defines an m by n matrix, assigns value(s) to its elements, then passes the matrix to function foo(). For whatever it's worth, I have declared foo() so...
11
by: Bob | last post by:
Hi, I compiled an application for the first time with no errors but following warnings: 1) variable declaration withoit an 'AS': Dim def() 2) variable 'myvar' is used before it has been...
7
by: GS | last post by:
in VS .net vb 2005 express, I failed to find the option for leaving out warning in the Errors tab but still leave Warning in the warning tab listing. Can someone give me some hints? thank you...
10
by: CodeBlaster | last post by:
Hi to all of you, I m new to C programming & i have a question *Generate a series such that after taking a number (e.g.99),when we press enter, the program should give an output which has no...
5
by: Steven W. Orr | last post by:
I'm trying again, since no response indicates that I'm not providing enough info. I have module M1 which has the following line in it: StartTime = safe_dict_get ( dic, 'starttime',...
5
by: drazet | last post by:
why the answer is 12 13 13? #include <stdio.h> int x; int m1(void); int c1(int x); int main(void){
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.