473,606 Members | 2,115 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Accessing flags

Hi

What's the best way in C to access the processor's flags register? I'm
thinking particularly of checking the carry or overflow flag after an
arithmetic operation.

Jun 27 '08 #1
9 5227
In article <pa************ *************** *@spamtrap.inva lid>,
kid joe <sp******@spamt rap.invalidwrot e:
>What's the best way in C to access the processor's flags register? I'm
thinking particularly of checking the carry or overflow flag after an
arithmetic operation.
There is no standard way of doing that in C; if you were able to
do it at all in your implementation, it would be by some
implementation-specific method.

Furthermore, on some processors, the status bits that exist are
not very persistant: if you had something like

a = b + c;

then after the addition of b + c then some processor status bit
might be set, but the subsequent move of the result into a might
end up changing the status bits.

--
"Whenever there is a hard job to be done I assign it to a lazy
man; he is sure to find an easy way of doing it."
-- Walter Chrysler
Jun 27 '08 #2
On Fri, 06 Jun 2008 22:36:14 +0100, kid joe
<sp******@spamt rap.invalidwrot e:
>Hi

What's the best way in C to access the processor's flags register? I'm
thinking particularly of checking the carry or overflow flag after an
arithmetic operation.
By reading the documentation for your system and learning the system
specific method it provides for doing this. Alternately, you could
ask in a newsgroup that discusses your system.
Remove del for email
Jun 27 '08 #3
On 6 Jun 2008 at 21:53, Walter Roberson wrote:
kid joe <sp******@spamt rap.invalidwrot e:
>>What's the best way in C to access the processor's flags register? I'm
thinking particularly of checking the carry or overflow flag after an
arithmetic operation.

Furthermore, on some processors, the status bits that exist are
not very persistant: if you had something like

a = b + c;

then after the addition of b + c then some processor status bit
might be set, but the subsequent move of the result into a might
end up changing the status bits.
Is there really any architecture where a mov instruction alters the
overflow or carry bit? It seems unlikely... On x86, moves don't modify
any flags at all.

Jun 27 '08 #4
kid joe wrote:
Hi

What's the best way in C to access the processor's flags register? I'm
thinking particularly of checking the carry or overflow flag after an
arithmetic operation.
There's no "best way" because as far as C is concerned
there's no way at all. One tiny problem is that C can be
(and has been) implemented on machines that have no flags.

Unfortunately, this leaves the C programmer in a bit of a
bind when it comes to overflow detection. For some operations
on some data types you can inspect the results to determine
whether there was an overflow. For example,

unsigned int ua = ..., ub = ...;
unsigned int sum = ua + ub;
if (sum >= ua) {
/* the mathematical sum was in representable range */
}
else {
/* the sum was out of range and has been reduced */
}

However, this approach won't necessarily work for all types.
For signed integers an overflow can produce fatal (or at least
unwelcome) effects as soon as it occurs, so you can't wait until
afterwards: You need to prevent it from happening in the first
place. That leads to ugly code like

int sa = ..., sb = ...;
int sum;
if (sa >= 0) {
if (sb <= INT_MAX - sa)
sub = sa + sb;
else {
/* sum would be too large */
}
}
else {
if (sb >= sa - INT_MIN)
sum = sa + sb;
else {
/* sum would be too small */
}
}

In actual practice it's rare to see code of this sort even
in a few places, and you'll just never see it applied everywhere
in a program! What people usually do, for better or worse, is
choose data types that will (they think) be able to handle the
expected range of data without overflowing, and then cross their
fingers and pretend overflow can never happen. Often they're
right, but the results can be spectacular when they're wrong ...

Some C compilers on some machines provide non-portable
extensions to get at such information (plus some promises on
how overflows are handled, so the information can be useful).
Note, though, that just "reading the flags register" is most
likely not sufficient, since you'd need to check it after each
potentially problematic operation:

y = ((a * x + b) * x) + c;
if (overflow_flag_ is_set()) /* sorry; too late */

/* instead: */
y = a * x;
if (overflow_flag_ is_set()) ...
y += b;
if (overflow_flag_ is_set()) ...
y *= x;
if (overflow_flag_ is_set()) ...
y += c;
if (overflow_flag_ is_set()) ...

What would be Really Nice would be a "latching flag" that would
be set by any overflow and remain set until explicitly cleared:

clear_overflow_ latch();
y = ((a * x + b) * x) + c;
if (overflow_latch _is_set()) ...

However, there's no such thing -- not even a "volatile" flag --
in C itself, presumably because it would be punishingly slow
to provide on many machines. (C follows the long-established
tradition that speed is more important than correctness. ;-)

--
Er*********@sun .com
Jun 27 '08 #5
kid joe wrote:
>
What's the best way in C to access the processor's flags register?
I'm thinking particularly of checking the carry or overflow flag
after an arithmetic operation.
They are not available, and in fact may not even exist. In any
standard C system.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #6
On Jun 6, 5:15*pm, Antoninus Twink <nos...@nospam. invalidwrote:
On *6 Jun 2008 at 21:53, Walter Roberson wrote:
kid joe *<spamt...@spam trap.invalidwro te:
>What's the best way in C to access the processor's flags register? I'm
thinking particularly of checking the carry or overflow flag after an
arithmetic operation.
Furthermore, on some processors, the status bits that exist are
not very persistant: if you had something like
* a = b + c;
then after the addition of b + c then some processor status bit
might be set, but the subsequent move of the result into a might
end up changing the status bits.

Is there really any architecture where a mov instruction alters the
overflow or carry bit? It seems unlikely... On x86, moves don't modify
any flags at all.

The 6800 would clear (set to zero) overflow and set (to values correct
for the data moved) the zero and sign flags on loads, stores and
register to register moves, although it left the carry alone in those
cases. The 6502 would set the zero and sign bits on loads and
register to register moves (but leave overflow and carry alone, and
altered no flags on stores).

The other thing to remember is that if the program has to do any sort
of address computation during the store, that might have to alter the
flags as well. Nor is there any guarantee that the CPU in question
has flags (most RISCs), or that the flag modifying instructions are
actually used. For example, on x86 a compiler could use MMX/SSE
instructions to add numbers, or use something like LEA to add. In
fact the use of LEA is pretty common, especially if the expression is
slightly more complex: say “a = b+2*c;”.
Jun 27 '08 #7
rio

"Eric Sosman" <Er*********@su n.comha scritto nel messaggio
news:1212790572 .671162@news1nw k...
kid joe wrote:
>Hi
y = ((a * x + b) * x) + c;
if (overflow_flag_ is_set()) /* sorry; too late */

/* instead: */
y = a * x;
if (overflow_flag_ is_set()) ...
y += b;
if (overflow_flag_ is_set()) ...
y *= x;
if (overflow_flag_ is_set()) ...
y += c;
if (overflow_flag_ is_set()) ...

What would be Really Nice would be a "latching flag" that would
be set by any overflow and remain set until explicitly cleared:

clear_overflow_ latch();
y = ((a * x + b) * x) + c;
if (overflow_latch _is_set()) ...
yes this can be the best

there is anhother way: define
a new integer type and an
aritmetic +, *, -, \
on that integer
so if somehting during the operation goes wrong the result is the integer
value OE [overflow error]
in the way x_NEW*y_NEW=x*y <= x * y not overflow
x_NEW*y_NEW=OE <=x*y overflow [or underflow?]
where "*" can be each possible operation

exaple
NewIntegerType a, x, b, c;
y = ((a * x + b) * x) + c;
if (y==OE) ...
However, there's no such thing -- not even a "volatile" flag --
in C itself, presumably because it would be punishingly slow
to provide on many machines. (C follows the long-established
tradition that speed is more important than correctness. ;-)

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

Jun 27 '08 #8


kid joe wrote:
Hi

What's the best way in C to access the processor's flags register? I'm
thinking particularly of checking the carry or overflow flag after an
arithmetic operation.
C compilers that support ISO 18037 can directly access the
processor flags limited only by the processor access limits.

_register_cc cc;
or
register volatile _CC cc;

if (cc.v == 1) // test overflow

int a,b;

a = b + cc.c; // add with carry
Regards

--
Walter Banks
Byte Craft Limited
Tel. (519) 888-6911
http://www.bytecraft.com
wa****@bytecraf t.com



Jun 27 '08 #9
In article <48************ ***@bytecraft.c om>,
Walter Banks <wa****@bytecra ft.comwrote:
>C compilers that support ISO 18037 can directly access the
processor flags limited only by the processor access limits.
I didn't recall what ISO 18037 was, so I checked briefly; it appears
to be C extensions for embedded processors. Potentially useful
if you work with embedded processors, but not applicable to other
situations.
--
"MAMA: Oh--So now it's life. Money is life. Once upon a time freedom
used to be life--now it's money. I guess the world really do change.
WALTER: No--it was always money, Mama. We just didn't know about it."
-- Lorraine Hansberry
Jun 27 '08 #10

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

Similar topics

3
2316
by: Xah Lee | last post by:
Python re module has methods flags and pattern. How to use these exactly? e.g. i tried print patternObj.flags() and the error is some "int object is not callable". newpattern=re.compile(ur'\w+',patternObj.flags())
7
1865
by: loquak | last post by:
Greets. I wonder which way would be the best for holding some state flags in terms of memory use and efficiency. a) struct FLAGS { bool flag1 : 1; bool flag2 : 1;
13
2051
by: Mark A. Odell | last post by:
I write a lot of drivers and there is inevitably some hardware register or buffer descriptor field called 'flags'. The flags are defined, typically, as bit positions. I was thinking I could get some compile-time type checking when assigning to a flag field but I don't think I can. Here's what I was thinking: typedef unsigned long HwFlag; struct HwThing { SomeType fieldOne;
6
5195
by: Alfred B. Thordarson | last post by:
I have a problem accessing a DLL using C#. I'm using C/FRONT with Navision's CFRONT.DLL, which contains the method: DBL_S32* DBL_NextKey(DBL_HTABLE hTable, DBL_S32* Key); typedef signed long int DBL_S32; In addition the documentation says that "hTable" is the "Handle to the table" and "Key" is "A table key or a NULL". Trying to access this
3
2549
by: Ignacio X. Domínguez | last post by:
Hi. I'm using the | operator to use multiple flags in a variable. For example: const int flag1 = 0x00000001; const int flag2 = 0x00000002; const int flag3 = 0x00000004; int Flags = flag2 | flag4 | flag1; Now I would like to remove flag2 from Flags without having to assign the
1
10441
by: Dwight.Dexter | last post by:
I have an enum variable. Is there some way to cast an int or BitArray and get my enum value? I have to communicate with an old C-style sever so I get an array of bits("0","1"). But I'm using an enum variable to store the data. public enum LaneCapabilities { MLT = 0, ACM = 1,
1
1442
by: Stephan Zaubzer | last post by:
Hi I relatively new to C# and at the moment I am having troubles accessing com objects within C#. I am working in VS.net. I add the com library I want to access to my references. Accessing classes exported in this com interfaces will throw a System.Security.SecurityException. (System.Security.Permissions.SecurityPermission) Status of failed permission: <IPermission class="System.Security.Permissions.SecurityPermission,
1
3843
by: Alexander Korsunsky | last post by:
Hi! Is it possible to extract the mode flags of a stream (FILE* stream or fstream - object), without looking at how the stream was opened? What I mean by mode flags is wether the stream is opened in read only mode, write only, binary and so on. I did not find any functions in C, but I found something similar in C++, the flags() member functio of an fstream object. I've tried to check the flags on ios_base::binary ios_base::in binary...
4
8081
by: Ralf | last post by:
Hallo, I'm trying to call a COM function from C#. The function has a parameter from the type array of IStream* (IStream**). The COM component (out-proc-server (.exe)) has the following code: (C++) STDMETHODIMP CIntf::SendFiles(int noOfStreams, IUnknown** dataStreams) {
0
8010
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
8429
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
8084
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
6761
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
5461
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
3922
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
2443
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
1
1550
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1287
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.