473,756 Members | 1,770 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Overflow Underflow


union SignedChoice{
long with_sign;
unsigned long without_sign;
};
int main()
{
SignedChoice data;

data.with_sign = -1;
//Right now, does the C++ Standard guarantee that
//data.without_si gn == MAX_ULONGINT?

//Similarly:

data.without_si gn = MAX_ULONGINT;

//Is data.with_sign now definitely == -1?

}
Is there any other interesting facts yous can give me?

-JKop
Jul 22 '05
38 8453
Ioannis Vranos wrote in news:cb******** ***@ulysses.noc .ntua.gr in
comp.lang.c++:
Rob Williscroft wrote:

3.9.1/3

Then JKOP is right!
#include <iostream>
union whatever
{
unsigned u;
signed i;
};
int main()
{
using namespace std;

whatever nice;

nice.i=-1;

cout<<nice.u<<" "<<static_cast< unsigned>(-1)<<endl;
}
Based on the standard nice.u above will always be equal to
numeric_limits< unsigned>::max( )!


No on a 1's complement machine (say 16 bit for example:) -1 will
be represented in binary as 10000000 00000001 high bit (sign bit)
and byte first. unsigned( -1 ) is 11111111 11111111 which is
std::numeric_li mits< unsigned >::max().

You must read the union member that was last assigned.

3.9.1/3 says that INT_MAX 01111111 1111111 has the same value
representation in signed and unsigned.

Doing:

nice.i = INT_MAX;
cout << nice.u;

is still UB, but in practice its only UB because the standard
says so. In theory (for example) a compiler could diagnose the
UB and refuse to compile, its UB, its free to *anything* it wants
and still be a conforming compiler.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #21
Ioannis Vranos wrote:
Based on the standard nice.u above will always be equal to
numeric_limits< unsigned>::max( )!

Actually the standard states:

"For each of the signed integer types, there exists a corresponding (but
different) unsigned integer type: “unsigned char”, “unsigned short int”,
“unsigned int”, and “unsigned long int,” each of which occupies the same
amount of storage and has the same alignment requirements (3.9) as the
corresponding signed integer type 40) ; that is, each signed integer
type has the same object representation as its corresponding unsigned
integer type. The range of nonnegative values of a signed integer type
is a subrange of the corresponding unsigned integer type, and the value
representation of each corresponding signed/unsigned type shall be the same.

....

40) See 7.1.5.2 regarding the correspondence between types and the
sequences of type-specifiers that designate them."

So the above leaves it possible the signed(-1) and unsigned(-1) to have
a different value representation. signed(-2) and unsigned(-2) to have a
different representation and so on.
So as far as I can get it, the union thing is not guaranteed to work.
Any comments?


Regards,

Ioannis Vranos
Jul 22 '05 #22
Rob Williscroft wrote:
#include <iostream>
union whatever
{
unsigned u;
signed i;
};
int main()
{
using namespace std;

whatever nice;

nice.i=-1;

cout<<nice.u<<" "<<static_cast< unsigned>(-1)<<endl;
}
No on a 1's complement machine (say 16 bit for example:) -1 will
be represented in binary as 10000000 00000001 high bit (sign bit)
and byte first. unsigned( -1 ) is 11111111 11111111 which is
std::numeric_li mits< unsigned >::max().

You must read the union member that was last assigned.

3.9.1/3 says that INT_MAX 01111111 1111111 has the same value
representation in signed and unsigned.

Yes.


Doing:

nice.i = INT_MAX;
cout << nice.u;

is still UB, but in practice its only UB because the standard
says so.

What do you mean? For non-negative values which are in range of both
types, they must have the same value representation.


Regards,

Ioannis Vranos
Jul 22 '05 #23
Ioannis Vranos wrote in news:cb******** ***@ulysses.noc .ntua.gr in
comp.lang.c++:
is still UB, but in practice its only UB because the standard
says so.

What do you mean? For non-negative values which are in range of both
types, they must have the same value representation.


Yes, what I mean I said just after the bit you quoted, here it is
again:

is still UB, but in practice its only UB because the standard
says so. In theory (for example) a compiler could diagnose the
UB and refuse to compile, its UB, its free to *anything* it wants
and still be a conforming compiler.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #24
Rob Williscroft wrote:
Yes, what I mean I said just after the bit you quoted, here it is
again:

is still UB, but in practice its only UB because the standard
says so.

Yes I meant, "where does the standard say so"?


Regards,

Ioannis Vranos
Jul 22 '05 #25
Ioannis Vranos <iv*@guesswh.at .grad.com> wrote:

Then JKOP is right!
Hardly
#include <iostream>

union whatever
{
unsigned u;
signed i;
};

int main()
{
using namespace std;
whatever nice;
nice.i=-1;
cout<<nice.u<<" "<<static_cast< unsigned>(-1)<<endl;
}
It's undefined behaviour to read any member of a union other than
the one that was most recently assigned (with the exception of the
case where the member read, and the most recently assigned member,
are 'struct's with a common initial sequence, and you read one of
the members of that common initial sequence).
Based on the standard nice.u above will always be equal to
numeric_limits< unsigned>::max( )!


C and C++ work on values, not representations . -1 when static_cast
to an unsigned type will always be the maximum value of that type,
regardless of representation.

On the other hand, the representation of (int)-1 and (unsigned)-1
need not be the same (AFAICS), so even if the union example was
not UB, it still would not 'work'.

I suspect that reinterpret_cas t<> will do what you are trying to do
with the union example (I don't have a 1's complement machine to
test it on though..)
Jul 22 '05 #26
Old Wolf posted:

It's undefined behaviour to read any member of a union other than
the one that was most recently assigned (with the exception of the
case where the member read, and the most recently assigned member,
are 'struct's with a common initial sequence, and you read one of
the members of that common initial sequence).


I know it's Undefined Behaviour to read from a double or a float without
prior initialization, ie.
double a;
float b;

a += 5.6;

b -= 6.2;
But... is it Undefined Behaviour to read from an uninitialized int? If
*not*, then contrary to you last post, there's nothing wrong with the
following:

union Chase
{
char black[sizeof(long)];
unsigned long blue;
};

int main()
{
Chase pursuit;

pursuit.black[0] = 5;
pursuit.black[1] = 2;
pursuit.black[2] = 6;
pursuit.black[3] = 88;

pursuit.blue += 4;
}
I last set it via black, but still there's nothing wrong with accessing it
via blue.
-JKop
Jul 22 '05 #27
JKop wrote:
But... is it Undefined Behaviour to read from an uninitialized int?

Actually it is.
Here are some definitions from the Standard:
1.3.12 undefined behavior
behavior, such as might arise upon use of an erroneous program construct
or erroneous data, for which this International Standard imposes no
requirements. Undefined behavior may also be expected when this
International Standard omits the description of any explicit definition
of behavior. [Note: permissible undefined behavior ranges from ignoring
the situation completely with unpredictable results, to behaving during
translation or program execution in a documented manner characteristic
of the environment (with or without the issuance of a diagnostic
message), to terminating a translation or execution (with the issuance
of a diagnostic message). Many erroneous program constructs do not
engender undefined behavior; they are required to be diagnosed. ]
1.3.13 unspecified behavior
behavior, for a well-formed program construct and correct data, that
depends on the implementation. The implementation is not required to
document which behavior occurs. [Note: usually, the range of possible
behaviors is delineated by this International Standard. ]"

As i have said in another message of mine, the union thing is not
guaranteed to work for values other than positive ones in the range
[0,maximum_posit ive_one_support ed_by_the_small er_range_type].


Regards,

Ioannis Vranos
Jul 22 '05 #28
Ioannis Vranos wrote:
JKop wrote:
But... is it Undefined Behaviour to read from an uninitialized int?


Actually it is.
Here are some definitions from the Standard:
1.3.12 undefined behavior
behavior, such as might arise upon use of an erroneous program construct
or erroneous data, for which this International Standard imposes no
requirements. Undefined behavior may also be expected when this
International Standard omits the description of any explicit definition
of behavior. [Note: permissible undefined behavior ranges from ignoring
the situation completely with unpredictable results, to behaving during
translation or program execution in a documented manner characteristic
of the environment (with or without the issuance of a diagnostic
message), to terminating a translation or execution (with the issuance
of a diagnostic message). Many erroneous program constructs do not
engender undefined behavior; they are required to be diagnosed. ]
1.3.13 unspecified behavior
behavior, for a well-formed program construct and correct data, that
depends on the implementation. The implementation is not required to
document which behavior occurs. [Note: usually, the range of possible
behaviors is delineated by this International Standard. ]"

As i have said in another message of mine, the union thing is not
guaranteed to work for values other than positive ones in the range
[0,maximum_posit ive_one_support ed_by_the_small er_range_type].

And another interesting behaviour is:

1.3.5 implementation-defined behavior
behavior, for a well-formed program construct and correct data, that
depends on the implementation and that each implementation shall document.


Regards,

Ioannis Vranos
Jul 22 '05 #29
Ioannis Vranos wrote in news:cb******** ***@ulysses.noc .ntua.gr in
comp.lang.c++:
Rob Williscroft wrote:
Yes, what I mean I said just after the bit you quoted, here it is
again:

is still UB, but in practice its only UB because the standard
says so.

Yes I meant, "where does the standard say so"?


Section 9 Classes, 9.5 Unions, paragraph 1.

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #30

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

Similar topics

7
8497
by: Oplec | last post by:
Hello, How can underflow and overflow of the basic arithmetic types be tested for using standard C++? For instance, if two long doubles are multiplied together, test whether or not the result is too large to fit in a long double? Thank you for your time, Oplec.
4
3554
by: aling | last post by:
Given: signed a, b; How to judge overflow of the sum of these two operands? Just use one *if* statement. Is this statement right? if ((a>0 && b>0 && sum<=0) || (a<0 && b<0 && sum>=0)) // overflow else // not overflow
2
6072
by: Paul Emmons | last post by:
Can anyone suggest example code, or how to proceed, in adding or subtracting two long long integers (I'm working in gcc with Linux, where a long long is 64 bits) and determining whether an overflow or underflow occurs, invalidating the result? I have written a solution in assembler. It's simple, thanks to the overflow flag. But without access to this part of the hardware in the C language, how would one do it? Thank you for your...
5
9232
by: Ian Pilcher | last post by:
I'm trying to figure out if an increment to a variable of an integer type, followed by a decrement, (or vice versa) is guaranteed to restore the variable to its initial value, even if the first operation causes the variable to overflow/underflow. In other words, if foo_t is an integer type, are the following two functions guaranteed to *always* return a non-zero value? int check_overflow(foo_t f) {
4
3604
by: glenn | last post by:
I have a COM Server I've written in C#. I have a client app I've written in Delphi that is calling the C# COM Server. However, one of the functions in the COM Server creates a form and during the creation process it receives the Overflow or Underflow in arithmetic operation error. I have traced it down to the section of the for where its registering the components... this.Controls.Add(this.cmd_exit); it doesn't matter which control...
4
4147
by: Tom | last post by:
I have a VB.NET framework 1.1 application that I am installing on my user's workstation. It works fine on EVERY machine except for one - on this one machine it generates a 'Overflow or underflow in the arithmetic operation' when I attempt to instantiate my first form, as so: Dim frm As New frmMyForm() Based on some things I saw here, I thought it might be that this workstation didn't have a MS Sans Seriff font on it (since that is the...
4
9951
by: Raymond | last post by:
Source: http://moryton.blogspot.com/2007/08/detecting-overflowunderflow-when.html Example from source: char unsigned augend (255); char unsigned const addend (255); char unsigned const sum (augend + addend); if (sum < augend)
2
3088
by: jou00jou | last post by:
Hi, I have trouble using sscanf and fgets to check for overflow. I will post the assignment specification so I could help whoever would kindly like to offer his/her help. ____________________________________________________________________________________ 1) The program should expect 2 decimal integers per line. Let's call these n1 and n2. 2) For each such input line it should output the value of n1 + 2 * n2 (followed by a newline...
11
3199
by: pereges | last post by:
Hi, I have written a small function that can (I think) deal with overflow/underflow while adding integers and divide by zero problem. Can some one please tell me if I have done it correctly ? Would it be safe to extend it to double precision floating point numbers since we know that there is always some margin for error while adding floating point numbers ? What other functions should I look to implement for my project ? #include...
0
9275
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
10034
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
9872
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
9843
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
8713
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
6534
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();...
1
3805
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
3358
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2666
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.