Path: csiph.com!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!border3.nntp.dca.giganews.com!Xl.tags.giganews.com!border1.nntp.dca.giganews.com!nntp.giganews.com!local2.nntp.dca.giganews.com!nntp.earthlink.com!news.earthlink.com.POSTED!not-for-mail NNTP-Posting-Date: Wed, 01 Aug 2012 08:57:28 -0500 Message-ID: <501935C7.5D52@mindspring.com> Date: Wed, 01 Aug 2012 09:57:27 -0400 From: pete Reply-To: pfiland@mindspring.com Organization: PF X-Mailer: Mozilla 3.04Gold (WinNT; I) MIME-Version: 1.0 Newsgroups: comp.lang.c Subject: Re: Restricted unsigned integer range would have been better? References: <5011E247.1F7B@mindspring.com> <5012954D.20C@mindspring.com> <5018AE22.152C@mindspring.com> <0.41a5266becbe1d48f128.20120801125152BST.87r4rq4yp3.fsf@bsb.me.uk> <50191E78.CDB@mindspring.com> <0.837a8fa3b84a81796f37.20120801142215BST.87lihy4uig.fsf@bsb.me.uk> Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Lines: 47 X-Usenet-Provider: http://www.giganews.com NNTP-Posting-Host: 4.154.220.165 X-Trace: sv3-kVx2msa+NtA53UIme9SASClq5qw5k/l8wXgqn51FUQghrl63L7okKDbPxaHbvZcV0AEo0NRx87h/CEw!Am65EjycpCHNN+/2WGcmRSX27T0M8xpgo/YjwS5/clLA7bwLYPmoEBQo2WUwTBLPmnUOUJgZrwUW!FieBdFZTxtg= X-Abuse-and-DMCA-Info: Please be sure to forward a copy of ALL headers X-Abuse-and-DMCA-Info: Otherwise we will be unable to process your complaint properly X-Postfilter: 1.3.40 X-Original-Bytes: 2916 Xref: csiph.com comp.lang.c:24053 Ben Bacarisse wrote: > > pete writes: > > > Ben Bacarisse wrote: > > >> > On 01/08/2012 06:18, pete wrote: > >> >> Philip Lantz wrote: > > >> >>> 5. while (*s != '\0') > >> >>> n = n * 10 + (*s - '0'); > > >> >> If n is of type int and also not negative, > >> >> then you could write without having to use parentheses > >> >> n = n * 10 - '0' + *s; > >> >> with no possibility of overflow. > >> > >> I don't understand that. > >> Did you mean "and also unsigned" rather than > >> "and also not negative"? > > > > No. > > It reminded me of a line from a toy atoi > > that I once wrote as an exercise. > > Ah! You meant that the parentheses can be removed without causing an > otherwise avoidable overflow, I think. Yes. That's what I meant. Thank you. > Both versions can overflow, but > the "bad" version (n = n * 10 + *s - '0') > can cause a needless overflow. I also think I should change the condition my loop from while (isdigit(*nptr)) { to while (*nptr != '\0') { similar to what Philip Lantz had. I think that the spirit of atoi is that it is supposed to be a simple function, which is only to be used when it is known that the input won't cause any problems. -- pete