473,326 Members | 2,048 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

strtol clarification

Since there's no strtoi function in standard C, I've been searching the
clc archives for the proper way to store the result of strtol to an
int. My search has yielded conflicting results. About half of the
results say to cast the result to an int. The other half say the cast
isn't necessary. And the third half say to compare the result to
INT_MAX and INT_MIN before assigning. Which is correct?

Kristo

Nov 14 '05 #1
14 3364
On Fri, 08 Apr 2005 07:48:47 -0700, Kristo wrote:
Since there's no strtoi function in standard C, I've been searching the
clc archives for the proper way to store the result of strtol to an
int. My search has yielded conflicting results. About half of the
results say to cast the result to an int. The other half say the cast
isn't necessary. And the third half say to compare the result to
INT_MAX and INT_MIN before assigning. Which is correct?


C will convert implicitly between int and long so the cast is not
necessary. Some compilers might decide to complain about a shortening
conversion since there is a risk of undefined behaviour - compilers can
complain about anything they like. The cast MAY eliminate such a
diagnostic. For correctness, yes, check the long value is in the range of
INT_MIN to INT_MAX before converting to int. If it isn't then you get the
undefined behaviour mentioned.

So casting/not casting makes no difference functionally, bounds checking
is necessary for correctness.

Lawrence

Nov 14 '05 #2
Kristo wrote on 08/04/05 :
Since there's no strtoi function in standard C, I've been searching the
clc archives for the proper way to store the result of strtol to an
int. My search has yielded conflicting results. About half of the
results say to cast the result to an int. The other half say the cast
isn't necessary. And the third half say to compare the result to
3 halves ?

"Fascinating" -- Dr Spock
INT_MAX and INT_MIN before assigning. Which is correct?


The latter.

--
Emmanuel
The C-FAQ: http://www.eskimo.com/~scs/C-faq/faq.html
The C-library: http://www.dinkumware.com/refxc.html

"There are 10 types of people in the world today;
those that understand binary, and those that dont."

Nov 14 '05 #3
On 8 Apr 2005 07:48:47 -0700, Kristo
<kr*******@gmail.com> wrote:
Since there's no strtoi function in standard C, I've been searching the
clc archives for the proper way to store the result of strtol to an
int. My search has yielded conflicting results. About half of the
results say to cast the result to an int. The other half say the cast
isn't necessary. And the third half say to compare the result to
INT_MAX and INT_MIN before assigning. Which is correct?


Yes. Or no.

Personally, I don't use an explicit cast unless the compiler I'm forced
to use produces warnings about loss of precision (in that case the
explicit cast says "yes, I intend to lose precision here"; I'd prefer
to turn the warning off but company policy says otherwise).

Doing the comparison with INT_MAX and INT_MIN is useful if you can take
appropriate action on failure and especially if the truncated result
will result in errors. However, it's more likely that the test should
be on the range of expected values, not on some implementation-defined
size of an int (i.e. the problem domain not the target implementation
domain -- if you can validly receive "32768" as an input but you only
have 16 bit signed int variables then it's a programming error not an
input error).

Chris C
Nov 14 '05 #4
Lawrence Kirby wrote:
On Fri, 08 Apr 2005 07:48:47 -0700, Kristo wrote:
Since there's no strtoi function in standard C, I've been searching
the clc archives for the proper way to store the result of strtol
to an int. My search has yielded conflicting results. About half
of the results say to cast the result to an int. The other half
say the cast isn't necessary. And the third half say to compare
the result to INT_MAX and INT_MIN before assigning. Which is
correct?

[snip details]
So casting/not casting makes no difference functionally, bounds
checking is necessary for correctness.


Ok thanks for clearing that up. Looks like it'll be worth my while to
write StrToInt and StrToUint to do the bounds checking.

<OT>
Do you happen to know if most (any) compilers provide strtoi and
strtoui as an extension?
</OT>

Kristo

Nov 14 '05 #5
Kristo wrote:

Since there's no strtoi function in standard C, I've been searching
the clc archives for the proper way to store the result of strtol
to an int. My search has yielded conflicting results. About half
of the results say to cast the result to an int. The other half
say the cast isn't necessary. And the third half say to compare
the result to INT_MAX and INT_MIN before assigning. Which is
correct?


Try applying some elementary reasoning to the problem. Under what
circumstances can the value stored in a long be stored in an int?
Do those circumstances depend on the actual value in that long? If
so, how does one check that they are suitable for an int?

Any time you see a cast, the code is very likely to be wrong.

--
"If you want to post a followup via groups.google.com, 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 #6
Lawrence Kirby <lk****@netactive.co.uk> writes:
[...]
C will convert implicitly between int and long so the cast is not
necessary. Some compilers might decide to complain about a shortening
conversion since there is a risk of undefined behaviour - compilers can
complain about anything they like. The cast MAY eliminate such a
diagnostic. For correctness, yes, check the long value is in the range of
INT_MIN to INT_MAX before converting to int. If it isn't then you get the
undefined behaviour mentioned.


Not quite. Converting a value from long to int leaves the value
unchanged if it can be represented as an int; otherwise (on overflow),
it either yields an implementation-defined result or raises an
implementation-defined signal (C99 6.3.1.3). C90 says the result is
implementation-defined; there's no mention of raising a signal (C90
6.2.1.2).

--
Keith Thompson (The_Other_Keith) 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 #7
"Emmanuel Delahaye" <em***@YOURBRAnoos.fr> writes:
[...]
"Fascinating" -- Dr Spock


<WAY_OT>
Dr. Benjamin Spock may well have said "Fascinating" some time in his
life, but you're probably thinking of Mr. Spock (who has the equivalent
of several doctorate degrees, but is never referred to as "Doctor").
</WAY_OT>

--
Keith Thompson (The_Other_Keith) 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 #8
Kristo wrote:
Since there's no strtoi function in standard C, I've been searching the
clc archives for the proper way to store the result of strtol to an
int. My search has yielded conflicting results. About half of the
results say to cast the result to an int. The other half say the cast
isn't necessary. And the third half say to compare the result to
INT_MAX and INT_MIN before assigning. Which is correct?
...


The latter is correct, meaning that you should to store the immediate
result in a 'long' object, check the range and then convert the result
(explicitly or implicitly) to the final 'int' value.

Note that it is also necessary to make sure that 'strtol' actually
succeeded, i.e., among other things, that the source representation
actually fits into a 'long' after conversion. If it doesn't, 'strtol'
returns 'LONG_MIN' or 'LONG_MAX'. If on your platform the range of
'long' is greater than that of 'int' (i.e. LONG_MIN < INT_MIN and
LONG_MAX > INT_MAX) then this check will be "automatically" included
into the aforementioned 'int'-range check. Otherwise, if the range of
'long' is the same as that of 'int', you'll have to do a separate check
by analyzing 'errno' value: 'strtol' will set 'errno' to 'ERANGE' in
"out of 'long' range" situations.

Of course, for portability reasons, it makes more sense to always follow
the latter approach, i.e. check the 'errno'.

--
Best regards,
Andrey Tarasevich
Nov 14 '05 #9
Kristo <kr*******@gmail.com> wrote:
Lawrence Kirby wrote:
On Fri, 08 Apr 2005 07:48:47 -0700, Kristo wrote:
Since there's no strtoi function in standard C, I've been searching
the clc archives for the proper way to store the result of strtol
to an int. My search has yielded conflicting results. About half
of the results say to cast the result to an int. The other half
say the cast isn't necessary. And the third half say to compare
the result to INT_MAX and INT_MIN before assigning. Which is
correct?


[snip details]
So casting/not casting makes no difference functionally, bounds
checking is necessary for correctness.


Ok thanks for clearing that up. Looks like it'll be worth my while to
write StrToInt and StrToUint to do the bounds checking.


Or use OpenBSD's strtonum(), which has shipped since 3.5 or 3.6. It's
actually meant as a replacement for atoi().

long long
strtonum(const char *nptr, long long minval, long long maxval,
const char **errstr);

http://www.openbsd.org/cgi-bin/man.cgi?query=strtonum.

http://www.openbsd.org/cgi-bin/cvswe...lib/strtonum.c

It's quite simple to use:

const char *errstr;
int i = strtonum(numstr,INT_MIN,INT_MAX,&errstr);

if (errstr)
/* fail gracefully */

/* continue */

Nov 14 '05 #10
Keith Thompson <ks***@mib.org> wrote:
"Emmanuel Delahaye" <em***@YOURBRAnoos.fr> writes:
[...]
"Fascinating" -- Dr Spock


<WAY_OT>
Dr. Benjamin Spock may well have said "Fascinating" some time in his
life, but you're probably thinking of Mr. Spock (who has the equivalent
of several doctorate degrees, but is never referred to as "Doctor").
</WAY_OT>


"I'm a science officer, Jim, not a doctor."

Richard
Nov 14 '05 #11

In article <42***************@yahoo.com>, CBFalconer <cb********@yahoo.com> writes:

Any time you see a cast, the code is very likely to be wrong.


Trivial counterexample: casting plain char to unsigned char when using
the functions from <ctype.h>. Suppressing unnecessary diagnostics,
as in the very situation described in this thread (after proper range
checking), is another.

Casts often indicate wrong, or at least infelicitous, code, but "any
time" and "very likely" are too strong.

--
Michael Wojcik mi************@microfocus.com

I will shoue the world one of the grate Wonders of the world in 15
months if Now man mourders me in Dors or out Dors
-- "Lord" Timothy Dexter, _A Pickle for the Knowing Ones_
Nov 14 '05 #12
On 12 Apr 2005 15:08:11 GMT, in comp.lang.c , mw*****@newsguy.com
(Michael Wojcik) wrote:

In article <42***************@yahoo.com>, CBFalconer <cb********@yahoo.com> writes:

Any time you see a cast, the code is very likely to be wrong.


Trivial counterexample: casting plain char to unsigned char when using
the functions from <ctype.h>.


This is /not/ a counterexample in any shape or form. Re-read CBF's
post, and see if the clause "very likely to be" helps.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #13
Mark McIntyre <ma**********@spamcop.net> writes:
On 12 Apr 2005 15:08:11 GMT, in comp.lang.c , mw*****@newsguy.com
(Michael Wojcik) wrote:
In article <42***************@yahoo.com>, CBFalconer
<cb********@yahoo.com> writes:

Any time you see a cast, the code is very likely to be wrong.


Trivial counterexample: casting plain char to unsigned char when using
the functions from <ctype.h>.


This is /not/ a counterexample in any shape or form. Re-read CBF's
post, and see if the clause "very likely to be" helps.


Can we not have yet another argument about the way a statement was
phrased?

It's arguably true that most casts are very likely to be wrong. Some
casts are valid, but it's possible that there are more useless casts
in real-world code than useful ones. I have no idea what the actual
numbers are; possibly the bulk of C code is better than I suspect it
is.

On the other hand, CBFalconer's statement could be interpreted to mean
that *any* given cast is very likely to be wrong, which is not true
since there are casts that are not "very likely to be wrong". I don't
believe that's what he meant, since he knows better. He could have
worded it better.

I presume we all agree that some casts (including Michael Wojcik's
example) are valid, and some other casts (such as casting the result
of malloc() are legal but "very likely to be wrong".

--
Keith Thompson (The_Other_Keith) 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 #14

In article <i9********************************@4ax.com>, Mark McIntyre <ma**********@spamcop.net> writes:
On 12 Apr 2005 15:08:11 GMT, in comp.lang.c , mw*****@newsguy.com
(Michael Wojcik) wrote:
In article <42***************@yahoo.com>, CBFalconer <cb********@yahoo.com> writes:

Any time you see a cast, the code is very likely to be wrong.


Trivial counterexample: casting plain char to unsigned char when using
the functions from <ctype.h>.


This is /not/ a counterexample in any shape or form. Re-read CBF's
post, and see if the clause "very likely to be" helps.


A swing and a miss, Mark.

Since I can read my own source code, I can see the casts I employ
when passing plain char arguments to ctype.h functions. Thus they
are instances of "any time [i] see a cast".

They are all correct; thus there is zero likelihood that the code
is wrong.

Thus this is a counterexample to Falconer's post, in precisely the
shape and form that I originally posted it. The adverbial phrase
(it's not the complete clause) "very likely to be", of which I was
perfectly cognizent when I composed my previous post, does not alter
that a whit.

Thanks for playing.

--
Michael Wojcik mi************@microfocus.com

This year's runner-up in the All-Usenet Creative Use Of English In A
Quasi-Legal But Probably Completely Ineffectual Signature Statement:

Disclaimer : I am a free denizen of this world and statements are of mine
and solly mine. Nobody dare sue me as you may end up even loosing your
attorney fees. -- Sridhar (ho********@hotmail.com)
Nov 14 '05 #15

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

Similar topics

1
by: Pavel Krcmar | last post by:
Hi, I'am a little bit confused. I tried this snippet (below) and ( endptr != NULL ) is true everytime. I was looking to http://www.mkssoftware.com/docs/man3/strtol.3.asp and then to...
13
by: Matthias Kluwe | last post by:
Hi! In C, my everyday usage of strtol looked like using char *end; strtol( text, &end, 10 ); to read an int/long and then checking end == ( text + strlen( text ) );
5
by: William Payne | last post by:
Hello, I am in the process of converting a C++ program to a C program. The user of the program is supposed to supply an integer on the command line and in the C++ version of the program I was using...
11
by: nrk | last post by:
Isn't: char s = "--4"; char *endptr; strtol(s, &endptr, 0); supposed to return 0 and set endptr to s? I have run into an implementation (not gcc, gcc does what I expect) that is returning...
10
by: Peter Dunker | last post by:
Hi, I will check a String which should contain a HEX value. I know that strtol is the right function for this job. But what happens when I will check a hex string with 8 bytes? That I can...
3
by: whisper | last post by:
Hello: I am trying to write code to read in a bunch of lines from stdin, each containing a (variable) number of integers and writing each integer in a separate line to stdout. I came up the...
2
by: Marlene Stebbins | last post by:
Suppose I'm using strtol() to convert a command line string to a number and I want to check that the input to strtol() is not non-numeric. strtol() returns zero if input is non-numeric, so I can...
3
by: dstevel | last post by:
The signature for strtol is: strtol( const char*, char**, int) So.. if we start with a passed "const char*" (pointer to const char), then we can't create a non-const char pointer pointer to...
8
by: lovecreatesbea... | last post by:
Does this part of C code call and check strtol() correctly? port = strtol(argv, &endptr, 10); if (argv == endptr){ fprintf(stderr, "%s\n", "Invalid port number form"); return 1; } if (port ==...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.