delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2003/07/28/20:15:09

From: "News Reader" <nospam AT aol DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: integer overflow
Date: Tue, 29 Jul 2003 02:00:59 +0200
Organization: UTA/netway (Customer)
Lines: 58
Message-ID: <bg4dkn$8et$1@newsreader1.netway.at>
References: <3F246120 DOT 63C3753C AT worldnet DOT att DOT net>
NNTP-Posting-Host: pat-ei.lucent.wellcom.at
X-Trace: newsreader1.netway.at 1059437015 8669 195.230.174.18 (29 Jul 2003 00:03:35 GMT)
X-Complaints-To: abuse AT netway DOT at
NNTP-Posting-Date: 29 Jul 2003 00:03:35 GMT
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2800.1158
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1165
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Your compiled code will not result in an overflow.
You are just getting an overflow warning from the
compiler, because the sign bit is affected twice during
the evaluation of your code. It was mentioned in this
thread that DJGPP defaults to signed 32-bit constants.

In order to prevent compiler warnings you can
change your code as follows:

    unsigned res;

    res=1; res<<=31; res--;    // was: (1<<31)-1;

Other examples which will work are:

    res = (1u<<31)-1;
    res = ((unsigned)1<<31)-1;
    res = (unsigned)(1<<31)-1;

Please note that using 'unsigned res' instead of
'unsigned long res' will not change anything because
DJGPP will produce 32-bit integers in both cases.


If your intention is to double the size of the variable
you have to use 'long long' in your declaration.
This will get you to 64 bits and your maximum
shift count will therefore be 63 (unsigned).

Unfortunately this does not help much because
your code will still be evaluated based on 32-bit
signed integer constants - unless you use one of
the following methods:

long long res;

     res = (1LL<<31)-1;
or
     res = ((long long)1<<31)-1;
or
     res=1; res<<=31; res--;




"Paul Cousoulis" <paulcsouls AT worldnet DOT att DOT net> wrote in message
news:3F246120 DOT 63C3753C AT worldnet DOT att DOT net...
>
> Why does this code result in an integer overflow?
>
> unsigned long res;
>
> res = (1<<31)-1;
>
> Thanks
> Paul


- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019