473,809 Members | 2,719 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Incrementing variables past limits

Hi there,

Does the ANSI standard say anything about incrementing variables past
their limits ?

When I compile code like this:

unsigned char x = 255;
x++;
printf ( "%d\n", x );

with GCC, the output is 0.

From an assembly point of view this seems to be logical behaviour, but is
it defined in the standard, or is it implementation dependant ??

I've googled for an answer, read K&R2 and the c.l.c FAQ but couldn't find
any decent answer..
Thanks in advance,
Bas Wassink.

Nov 14 '05 #1
26 4163
Bas Wassink wrote:
Hi there,

Does the ANSI standard say anything about incrementing variables past
their limits ?

When I compile code like this:

unsigned char x = 255;
x++;
printf ( "%d\n", x );

with GCC, the output is 0.

From an assembly point of view this seems to be logical behaviour, but is
it defined in the standard, or is it implementation dependant ??

I've googled for an answer, read K&R2 and the c.l.c FAQ but couldn't find
any decent answer..


The result is well-defined for unsigned integers: they
obey the rules of modular ("clock") arithmetic.

For unsigned integers, there are no guarantees. The
program may trap, or may deliver some implementation-defined
result. Most implementations "wrap around" from the most
positive to the most negative value, but the C language
itself doesn't promise this behavior.

--
Er*********@sun .com

Nov 14 '05 #2
Bas Wassink <id******@email .org> writes:
Does the ANSI standard say anything about incrementing variables past
their limits ?


Yes. Unsigned integer types wrap around. With other types it's
unpredictable and you should avoid doing out-of-bounds arithmetic
with them.
--
"We put [the best] Assembler programmers in a little glass case in the hallway
near the Exit sign. The sign on the case says, `In case of optimization
problem, break glass.' Meanwhile, the problem solvers are busy doing their
work in languages most appropriate to the job at hand." --Richard Riehle
Nov 14 '05 #3
<cr**********@n ews1brm.Central .Sun.COM>
Eric Sosman <er*********@su n.com> wrote:
For unsigned integers, there are no guarantees. The ^^^^^^^^ (I know you meant "signed" :) program may trap, or may deliver some implementation-defined
result. Most implementations "wrap around" from the most
positive to the most negative value, but the C language
itself doesn't promise this behavior.


--
Christopher Benson-Manica
ataru(at)cybers pace.org
Nov 14 '05 #4
Christopher Benson-Manica wrote:
<cr**********@n ews1brm.Central .Sun.COM>
Eric Sosman <er*********@su n.com> wrote:

For unsigned integers, there are no guarantees. The


^^^^^^^^ (I know you meant "signed" :)


I know you're right. Sorry about that.

--
Er*********@sun .com

Nov 14 '05 #5
Bas Wassink <id******@email .org> writes:
Does the ANSI standard say anything about incrementing variables past
their limits ?

When I compile code like this:

unsigned char x = 255;
x++;
printf ( "%d\n", x );

with GCC, the output is 0.

From an assembly point of view this seems to be logical behaviour, but is
it defined in the standard, or is it implementation dependant ??

I've googled for an answer, read K&R2 and the c.l.c FAQ but couldn't find
any decent answer..


For unsigned types, overflow has well-defined behavior; the result
wraps around. More precisely, the result is reduced modulo the number
that is one greater than the largest value that can be represented by
the resulting type. For unsigned char (assuming UCHAR_MAX==256) , the
value 256 reduces to 0; gcc is behaving correcly.

For signed types, overflow causes undefined behavior. Wraparound is
fairly common, but you shouldn't depend on it; some implementations
may produce a trap. (A conversion to a signed type, if the value
cannot be represented, either yields an implementation-defined result
or raises an implementation-defined signal.)

--
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 #6
Thank you for your quick reply, this will help me with writing clean
and portable 6502/6510-emulation code..

Bas Wassink
Nov 14 '05 #7
Bas Wassink wrote:
Does the ANSI standard say anything about incrementing variables past
their limits ?


Others have explained the rules for signed and unsigned integers. Also
note, however, that casting from signed to unsigned, incrementing, and
then casting back won't work. It's the last step that fails; a cast from
an unsigned value to a signed type that cannot represent that value is
implementation-defined (ref C99 6.3.1.3.3). If performance isn't a big
deal, the easiest way to increment a signed integer is a branch:

#include <limits.h>

int signed_incr(int i) {
if (i == INT_MAX)
i = INT_MIN;
else
i++;
}

--
Derrick Coetzee
I grant this newsgroup posting into the public domain. I disclaim all
express or implied warranty and all liability. I am not a professional.
Nov 14 '05 #8
Keith Thompson wrote:
Bas Wassink <id******@email .org> writes:
Does the ANSI standard say anything about incrementing variables past their limits ?

When I compile code like this:

unsigned char x = 255;
[Note that 255 need not be the limit for unsigned char.]
x++;
printf ( "%d\n", x );

with GCC, the output is 0.

From an assembly point of view this seems to be logical behaviour, but is it defined in the standard, or is it implementation dependant ??
For unsigned types, overflow has well-defined behavior; the result
wraps around. More precisely, the result is reduced modulo the

number that is one greater than the largest value that can be represented by
the resulting type. For unsigned char [assuming UCHAR_MAX==255], the
value 256 reduces to 0; gcc is behaving correcly.


Unsigned short has scope for problems...

unsigned short us = -1;
us++; /* UB if USHRT_MAX == INT_MAX */
The paranoid can safely use...

us += 1u;

--
Peter

Nov 14 '05 #9
Derrick Coetzee wrote:
Bas Wassink wrote:
Does the ANSI standard say anything about incrementing variables past
their limits ?

Others have explained the rules for signed and unsigned integers. Also
note, however, that casting from signed to unsigned, incrementing, and
then casting back won't work. It's the last step that fails; a cast from
an unsigned value to a signed type that cannot represent that value is
implementation-defined (ref C99 6.3.1.3.3). If performance isn't a big
deal, the easiest way to increment a signed integer is a branch:

#include <limits.h>

int signed_incr(int i) {
if (i == INT_MAX)
i = INT_MIN;
else
i++;
}


Of course, the above would not actually modify the original
value, and doesn't specify a return value, but I think we all
know what you meant.

Actually, in the vast majority of cases, it would be much better
to indicate an error when (i == INT_MAX) then to silently roll
it. I generally check explicitly for overflow on every arithmetic
operation that might cause one.

As an absurdly extreme--but true--case, failure to catch such a
rollover caused massive radiation overexposure, and even death,
to patients treated by the infamous Therac-25 liniar accelerator
used for radiation therapy.

http://courses.cs.vt.edu/~cs3604/lib.../Therac_1.html
Nov 14 '05 #10

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

Similar topics

8
2165
by: BigMan | last post by:
I wonder if the C++ standard says what should happen if I increment a pointer to a one-past-the-end value. I think it says that it is perfectly legal to increment a pointer to the last element element in an array - I get a pointer to one-past-the-end value. It is guaranteed that such a value exists for any array, so I always get a valid pointer to something (I do not care what it is). So, my question is what if I go further and increment...
10
7158
by: Antanas | last post by:
The problem is that when AddID is used multiple times in the same select statement, it returns the same value in all places. How could I force function AddID to increment OBJECTID sequence? Here is a basic sample of usage: SELECT AddID(), AddID(), AddID(), column1 from table1 Here is how AddID looks like:
27
8986
by: Erik de Castro Lopo | last post by:
Hi all, The GNU C compiler allows a void pointer to be incremented and the behaviour is equivalent to incrementing a char pointer. Is this legal C99 or is this a GNU C extention? Thanks in advance. Erik
10
4609
by: pozz | last post by:
Hi all, I need to write a simple incrementing/decrementing function like this: unsigned char change( unsigned char x, unsigned char min, unsigned char max, signed char d); x is the value to increase/decrease min is the minimum value that x can assume max is the maximum value that x can assume
13
2123
by: deepak | last post by:
Hi In the following function how the memory 'll be allocated. 1) Will it allocate memory for all the char's together or allocate for first char. then for int then for float and after this only second char in the function gets memory. 2) If i declare variables where the size of al variables gone beyond sizeof stack (assume it is 1000) what 'll happen? voud foo( int a, innt b)
0
1482
by: Aarchaic | last post by:
Hello i have problem my session variables seem to disapear as i go along i've created this code to ilustrate whats happening First off i just post 3 detials like a name a age and a favourite number. that in turn goes to the next page where its being picked up by the php code and put into the Global Variable. the page uses the variables with no problem and you can select a link to go onto the next page where the number is being...
53
4828
by: subramanian100in | last post by:
I saw this question from www.brainbench.com void *ptr; myStruct myArray; ptr = myArray; Which of the following is the correct way to increment the variable "ptr"? Choice 1 ptr = ptr + sizeof(ptr);
1
29393
weaknessforcats
by: weaknessforcats | last post by:
C++: The Case Against Global Variables Summary This article explores the negative ramifications of using global variables. The use of global variables is such a problem that C++ architects have called it polluting the global namespace. This article explores what happens when the global namespace becomes polluted and how to avoid this condition. The opinions expressed in this article are those of the author alone although many have...
9
3378
by: subramanian100in | last post by:
The following portion is from c-faq.com - comp.lang.c FAQ list · Question 6.13 int a1 = {0, 1, 2}; int a2 = {{3, 4, 5}, {6, 7, 8}}; int *ip; /* pointer to int */ int (*ap); /* pointer to array of int */\ ap = &a1; printf("%d\n", **ap);
0
9721
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
10376
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
10383
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
9200
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
6881
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
5550
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
5688
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4332
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
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.