473,804 Members | 2,243 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Confirm this is Standard code

I've got two bits of code that I would like some more experienced folks
to check for conformance to the Standard. I've tried my best to read
the standard and search around and I think and hope this code contains
no cause for concern.

/* taking absolute value of signed integer */
int32 val;
uint32 abs_val;

val = -492;

if(val < 0)
abs_val = -(uint32)val;

I have done my reading of the standard on this and searching around and
it seems the above is fine by the standard. Just want to make sure
because my lint warns about "Expected signed type".
Also please look at the code below and tell me if there is anything to
worry about as far as being non-standard. Just a note, the absolute
value of shiftAmt has already been pre-conditioned and is guaranteed
not to overflow an int16 so don't warn me about that possibly
overflowing and resulting in U.B..

int32 foo(int16 x, int16 shiftAmt)
{
int32 ret;

...
/* code block dealing with x < 0, shiftAmt < 0 */
ret = -((int32)((-(uint32)x) << (-shiftAmt)));
}

Thanks.

Nov 14 '05
18 1514
joshc wrote:
Jack Klein wrote:

.... snip ...

I still don't understand why you are writing code this way. Why
have you written the code in such an unusual and complex manner?

Again, post an explanation of what it is you are trying to do,
what the values are and what you need to do to them. There must
be a simpler way to write code to do what you need.


If you want the whole story I can tell you offline. Let me know.


No, you are the one who wants help. Jack is telling you to explain
what you are trying to do, and you may get some help. Simply
squalling that you want to square the circle won't go far. You may
get told that your objectives are off-topic, but that doesn't seem
likely in this case.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #11
On Sun, 03 Apr 2005 17:02:55 +0000, Walter Roberson wrote:
In article <pa************ *************** @netactive.co.u k>,
Lawrence Kirby <lk****@netacti ve.co.uk> wrote:
Would the cast not be processed before the unary minus?
That seems to be the intent.


Thanks for the detailed explanation, Lawrence
if(val < 0)
abs_val = (uint32)(-val);

The problem here is that -val can result in undefined behaviour which is
what the code is trying to avoid.


If I understand correctly, the undefined behaviour would be at
the boundary condition, where val is the most negative value.


That is the problem case, specifically when INT32_MIN has a greater
magnitude than INT32_MAX.
Perhaps special case that particular value?

if (val == INT32_MIN) abs_val = 0;
Better would be if (val < -INT32_MAX) because C doesn't require minimum
values to have a larger magnitude than maximum ones.
else if (val < 0) abs_val = -val;
else abs_val = val;


This is more complex and probably less efficient which might be relevant
to some people. abs_val = (uint32)(-val); produces the correct value
(rather than 0) for INT32_MIN if uint32 can represent it. Once you see
what it is doing this is a simple and clean solution to the problem. It
can produce an incorrect result (0) in rare to non-existant
circumstances when the correct result is not representable, but it
doesn't have any undefined behaviour.

Lawrence
Nov 14 '05 #12

CBFalconer wrote:
joshc wrote:
Jack Klein wrote:

... snip ...

I still don't understand why you are writing code this way. Why
have you written the code in such an unusual and complex manner?

Again, post an explanation of what it is you are trying to do,
what the values are and what you need to do to them. There must
be a simpler way to write code to do what you need.


If you want the whole story I can tell you offline. Let me know.


No, you are the one who wants help. Jack is telling you to explain
what you are trying to do, and you may get some help. Simply
squalling that you want to square the circle won't go far. You may
get told that your objectives are off-topic, but that doesn't seem
likely in this case.


My question has already been answered so that indicates that the
information I gave was sufficient for people to address the question. I
just wanted someone to confirm that was standard C and wasn't really
looking for advice on how to "better" write my algorithm.

Anyhow, since people seem interested, what that code is part of is a
fixed-point subtraction routine. I need to subtract an unsigned
fixed-point number from a signed fixed-pt number. In particular, in
that "odd" looking code, int16 x is the signed fixed-point number which
I am trying to scale to match the radix point position of the other
operand. Please don't ask me why signed and unsigned types are involved
in the subtraction, that is beyond my control and I also think it's
stupid.

Thanks for your help.

Nov 14 '05 #13

Lawrence Kirby wrote:
On Sun, 03 Apr 2005 17:02:55 +0000, Walter Roberson wrote:
snip...
The problem here is that -val can result in undefined behaviour which iswhat the code is trying to avoid.


If I understand correctly, the undefined behaviour would be at
the boundary condition, where val is the most negative value.


That is the problem case, specifically when INT32_MIN has a greater
magnitude than INT32_MAX.
Perhaps special case that particular value?

if (val == INT32_MIN) abs_val = 0;


Better would be if (val < -INT32_MAX) because C doesn't require

minimum values to have a larger magnitude than maximum ones.
else if (val < 0) abs_val = -val;
else abs_val = val;
This is more complex and probably less efficient which might be

relevant to some people. abs_val = (uint32)(-val); produces the correct value
(rather than 0) for INT32_MIN if uint32 can represent it. Once you see what it is doing this is a simple and clean solution to the problem. It can produce an incorrect result (0) in rare to non-existant
circumstances when the correct result is not representable, but it
doesn't have any undefined behaviour.


Lawrence, I'm a little confused by what seems to me to be a disparity
between what you said a few posts above and what you say in this post.
In this post you say that abs_val = (uint32)(-val) doesn't have any
undefined behavior. I thought you confirmed a few posts above that it
_does_ have undefined behavior if val=INT32_MIN and abs(INT32_MIN) >
INT32_MAX.

I may be misunderstandin g your post so please clarify.

Thanks.

Nov 14 '05 #14
Lawrence Kirby wrote:
.... snip ...
This is more complex and probably less efficient which might be
relevant to some people. abs_val = (uint32)(-val); produces the
correct value (rather than 0) for INT32_MIN if uint32 can
represent it. Once you see what it is doing this is a simple and
clean solution to the problem. It can produce an incorrect result
(0) in rare to non-existant circumstances when the correct result
is not representable, but it doesn't have any undefined behaviour.


Except that "(uint32)(-val)" for val == INT_MIN should produce the
value 0 for the normal value of UINT_MAX.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #15

Jack Klein wrote:
What puzzles me is WHY you want to write code like this.

On 2 Apr 2005 14:09:21 -0800, "joshc" <jo********@gma il.com> wrote in
comp.lang.c:
/* taking absolute value of signed integer */
int32 val;
uint32 abs_val;

val = -492;

if(val < 0)
abs_val = -(uint32)val;
Why not just:

abs_val = abs(val);

...after including <stdlib.h>? Or just:

abs_val = val > 0 ? val : -val;

In any case, the result of the code is well-defined if val is

negative unless it happens to be the minimum possible value and has a magnitude of on greater than the maximum positive value.
I suppose he tried to avoid exactly your "unless" case.

I have done my reading of the standard on this and searching around and it seems the above is fine by the standard. Just want to make sure
because my lint warns about "Expected signed type".

Also please look at the code below and tell me if there is anything to worry about as far as being non-standard. Just a note, the absolute
value of shiftAmt has already been pre-conditioned and is guaranteed not to overflow an int16 so don't warn me about that possibly
overflowing and resulting in U.B..


Pre-conditioned to be what? Since you are casting to a 32 bit type
before the shift, and returning a 32 bit value, what might overflow a
16 bit type doesn't make any difference.
int32 foo(int16 x, int16 shiftAmt)
{
int32 ret;

...
/* code block dealing with x < 0, shiftAmt < 0 */
ret = -((int32)((-(uint32)x) << (-shiftAmt)));


If shiftAmt was between 0 and -31 inclusive, this has well defined
results but looks quite bizarre. If shiftAmt is positive or less

than -32, it has undefined results.


Is that they are well defined in the sense that they are implementation
defined? Doesn't every argument pair that creates something > INT32_MAX
invoke implementation defined behaviour at the (int32) cast (e.g.
foo(-2,-31))?
BTW, how are integer promotions executed on extended integer types? Are
they left untouched even when an int is wider than a int32_t?

Mark

Nov 14 '05 #16

CBFalconer wrote:
Lawrence Kirby wrote:

... snip ...

This is more complex and probably less efficient which might be
relevant to some people. abs_val = (uint32)(-val); produces the
correct value (rather than 0) for INT32_MIN if uint32 can
represent it. Once you see what it is doing this is a simple and
clean solution to the problem. It can produce an incorrect result
(0) in rare to non-existant circumstances when the correct result
is not representable, but it doesn't have any undefined behaviour.


Except that "(uint32)(-val)" for val == INT_MIN should produce the
value 0 for the normal value of UINT_MAX.


How??? The cast is happening after the negation so I don't see how this
isn't undefined behavior in the case I mentioned where you have
|INT_MIN| > INT_MAX.

Nov 14 '05 #17
joshc wrote:

CBFalconer wrote:
Lawrence Kirby wrote:

... snip ...

This is more complex and probably less efficient which might be
relevant to some people. abs_val = (uint32)(-val); produces the
correct value (rather than 0) for INT32_MIN if uint32 can
represent it. Once you see what it is doing this is a simple and
clean solution to the problem. It can produce an incorrect result
(0) in rare to non-existant circumstances when the correct result
is not representable, but it doesn't have any undefined behaviour.


Except that "(uint32)(-val)" for val == INT_MIN should produce the
value 0 for the normal value of UINT_MAX.


How??? The cast is happening after the negation so I don't see how
this isn't undefined behavior in the case I mentioned where you
have |INT_MIN| > INT_MAX.


You're right. I'm wrong.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #18
On 2 Apr 2005 14:09:21 -0800,
joshc <jo********@gma il.com> wrote:

I've got two bits of code that I would like some more experienced folks
to check for conformance to the Standard. I've tried my best to read
the standard and search around and I think and hope this code contains
no cause for concern.

/* taking absolute value of signed integer */
int32 val;
uint32 abs_val;


I would have thought that int32 and uint32 were not standards conform
but int32_t and uint32_t as defined in <stdint.h> are on platform where
such types are supported.

int32 and uint32 could be user defined types in part of the code not
listed, though.

Villy
Nov 14 '05 #19

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

Similar topics

7
18443
by: Andy Fish | last post by:
Hi, now I know what the alert() function does, but can anyone tell me where I can find the specification or standards for functions like alert() and confirm(). They don't seem to be part of the ECMAScript language but aren't part of the DOM either. Now we seem to be finally reaching a stage of standards-compliant browsers, there seems to be a bit of a gap here.
0
1585
by: Joe Finsterwald | last post by:
Recently I needed to add a confirm to a LinkButton that called a JavaScript function on success, and did nothing on failure. I found documentation on adding a confirm, but not on how to place a confirm in a conditional. In any case, I've found the answer and I thought I'd share. In VB.NET (in the code behind in VS.NET) Adding just a confirm...
1
3832
by: freshRecruit | last post by:
Hi, I am having a problem, and is driving me nuts and my deadline is fast approaching. Please do help me.. This is a webapplication with a usercontrol which has some buttons for adding, deleting and updating to a database. When the user clicks the "Add" button than the information provided is validated against the database. If the validation succeeds than the information is added to the database. If not a confirm box is shown and if...
1
2461
by: chris | last post by:
Hi, In ASP.NET page, when my user tries to edit a record in gridview, I need to display a confirmation message, if another user is editing the same record. Since the confirmation message will not be displayed on a button click, I am using the following: 'check whether another user is editing record IF another user is editing record THEN
4
10026
by: tfsmag | last post by:
Okay, I have a project management app i'm writing and in the left hand menu i have a treeview control that is populated with each project... in child nodes under each project node I have an "edit" and a "delete" node. I have the functionality of the edit and delete working fine, my issue is now however that I cannot seem to find a way to add an "onclick" event that fires a confirm box. I've tried this method.. treenode.Text = "<a...
8
4036
by: rn5a | last post by:
I have gone through a no. of posts in this NewsGroup regarding my problem but alas, couldn't come across one which would have helped me in resolving the issue. My problem is this: An ASPX Form has a Button. When the Button is clicked, I want a JavaScript confirm dialog to pop-up with the options 'OK' & 'Cancel'. I have done this using the following code: Sub Page_Load(....) btnClick.Attributes.Add("OnClick", "javascript:return...
4
7505
by: mamun | last post by:
Hi All, I have the following situation and am looking for answer in C#. I have a datagrid and putting checkbox next to each record. In the header I have a Delete button. I want users to checkchekboxes and click the Delete button. That will show a confirmation dialog message with the items they choose to delete.
13
2128
by: MikeC | last post by:
I read in the book Javascript The Definitive Guide by David Flanagan the following in reference to the use of alert, confirm, and prompt. "Although these dialog methods are extremely simple and easy to use, good design dictates that you use them sparingly, if at all. Dialog boxes like these are not a common feature of the web paradigm, and they have become much less common now that more capable web browsers support scripting of the...
5
4026
by: leosarasua | last post by:
I am writing a page in French and I need to create a confirm box, but I want to change the labels of the buttons from "OK" and "Cancel" into "Oui" and "Non". I've looked around and it seems impossible to do this, so my question is: why is the confirm method so restrictive? All it needs is a question string and two labels for the true and false buttons. Why was it defined with only one parameter, instead of, let's say one mandatory and...
0
9715
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
9595
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
10352
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
10354
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
9175
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
5535
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
5673
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3835
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3002
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.