473,796 Members | 2,501 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 #1
18 1512
On 2 Apr 2005 14:09:21 -0800, "joshc" <jo********@gma il.com> wrote in
comp.lang.c:
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.
What puzzles me is WHY you want to write code like this.
/* 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 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.
}

Thanks.


Can you describe in words exactly what it is you are trying to do with
this code? Whatever it is, I am pretty sure that there is a much less
convoluted way to write it.

--
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.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #2
In article <11************ **********@g14g 2000cwa.googleg roups.com>,
joshc <jo********@gma il.com> wrote:
/* taking absolute value of signed integer */
int32 val;
uint32 abs_val;

val = -492;

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


Would the cast not be processed before the unary minus? I could be wrong
but that code -looks- to me to be doing the following:

1) take a negative number and make it into an unsigned value
(I would have to re-read the standard to see what it says
about exactly what would happen)
2) does a unary minus on the unsigned value
(I would have to re-read the standard to see what unary minus
means when applied to an unsigned value)
3) sees that the value is to be assigned to an unsigned value, so
potentially converts the value again.

It would make more sense to me if the code were

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

at which point the cast would merely be redundant, with no
possibility of a triple conversion.
--
Would you buy a used bit from this man??
Nov 14 '05 #3
Jack Klein wrote:
On 2 Apr 2005 14:09:21 -0800, "joshc" <jo********@gma il.com> wrote in
comp.lang.c:
Why not just:

abs_val = abs(val);
This is code for an embedded system, i.e a freestanding implementation.

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.


Yeah, pre-conditioned to ensure what you describe above(0 to -31).

Thanks.

Nov 14 '05 #4

Walter Roberson wrote:
In article <11************ **********@g14g 2000cwa.googleg roups.com>,
joshc <jo********@gma il.com> wrote:
/* taking absolute value of signed integer */
int32 val;
uint32 abs_val;

val = -492;

if(val < 0)
abs_val = -(uint32)val;
Would the cast not be processed before the unary minus? I could be

wrong but that code -looks- to me to be doing the following:

1) take a negative number and make it into an unsigned value
(I would have to re-read the standard to see what it says
about exactly what would happen)
2) does a unary minus on the unsigned value
(I would have to re-read the standard to see what unary minus
means when applied to an unsigned value)
3) sees that the value is to be assigned to an unsigned value, so
potentially converts the value again.

It would make more sense to me if the code were

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

at which point the cast would merely be redundant, with no
possibility of a triple conversion.
--
Would you buy a used bit from this man??

Basically the reason I do this is so that I don't get signed integer
overflow because that results in undefined behavior. On the other hand,
dealing with unsigned integers there is no overflow and all arithmetic
operations are performed mod UINT_MAX+1 or whatever the relevant limit
is.

Nov 14 '05 #5
On Sat, 02 Apr 2005 23:46:46 +0000, Walter Roberson wrote:
In article <11************ **********@g14g 2000cwa.googleg roups.com>,
joshc <jo********@gma il.com> wrote:
/* taking absolute value of signed integer */
int32 val;
uint32 abs_val;

val = -492;

if(val < 0)
abs_val = -(uint32)val;
Would the cast not be processed before the unary minus?


That seems to be the intent.
I could be wrong
but that code -looks- to me to be doing the following:

1) take a negative number and make it into an unsigned value
(I would have to re-read the standard to see what it says
about exactly what would happen)
It says the result is the value you get by adding one more than the
largest value representable in the unsigned type. Call that largest value
UINT32_MAX then the result is aritmetically val + UINT32_MAX+1.
-(uint32)val is then -val-(UINT32_MAX+1). To bring that back into
a representable value when it is negative we must add UINT32_MAX+1 again
giving -val-(UINT32_MAX+1)+ (UINT32_MAX+1) i.e. -val. This gives us the
result we want as an unsigned value. The only situation where this "fails"
is when the absolute value of val is not representable as a uint32, in
that case the result turns out to be zero. That's unlikely because
unsigned types usually have a larger positive range then their
corresponding signed types.
2) does a unary minus on the unsigned value
(I would have to re-read the standard to see what unary minus
means when applied to an unsigned value)
3) sees that the value is to be assigned to an unsigned value, so
potentially converts the value again.

It would make more sense to me if the code were

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

at which point the cast would merely be redundant, with no
possibility of a triple conversion.


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

Lawrence
Nov 14 '05 #6
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.
Perhaps special case that particular value?

if (val == INT32_MIN) abs_val = 0;
else if (val < 0) abs_val = -val;
else abs_val = val;

--
Walter Roberson is my name,
And Usenet is my nation.
Cyber space is my dwelling pace,
And flames my destination.
Nov 14 '05 #7
On 2 Apr 2005 15:50:44 -0800, "joshc" <jo********@gma il.com> wrote in
comp.lang.c:
Jack Klein wrote:
On 2 Apr 2005 14:09:21 -0800, "joshc" <jo********@gma il.com> wrote in
comp.lang.c:
Why not just:

abs_val = abs(val);


This is code for an embedded system, i.e a freestanding implementation.


I understand all about embedded systems, that what I've been doing for
25 years.

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.


Yeah, pre-conditioned to ensure what you describe above(0 to -31).

Thanks.


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.

--
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.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 14 '05 #8
Walter Roberson wrote:
Lawrence Kirby <lk****@netacti ve.co.uk> wrote:
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.
Perhaps special case that particular value? ...


Or find a (big-picture) algorithm that doesn't require the
magnitude of a signed int in the first place.

--
Peter

Nov 14 '05 #9

Jack Klein wrote:
On 2 Apr 2005 15:50:44 -0800, "joshc" <jo********@gma il.com> wrote in
comp.lang.c:
Jack Klein wrote:
On 2 Apr 2005 14:09:21 -0800, "joshc" <jo********@gma il.com> wrote in comp.lang.c:
Why not just:

abs_val = abs(val);
This is code for an embedded system, i.e a freestanding implementation.
I understand all about embedded systems, that what I've been doing for 25 years.
Heh, sorry, I didn't mean it to sound the way you took it. I don't have
25 years experience and that's why I am asking these questions :).

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.


Yeah, pre-conditioned to ensure what you describe above(0 to -31).

Thanks.


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.

Nov 14 '05 #10

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

Similar topics

7
18442
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
2460
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
10025
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
4034
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
7504
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
2127
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...
1
10176
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
10013
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7550
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6792
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
5443
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
5576
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4119
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
3733
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2927
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.