From: Martin Ambuhl User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax) X-Accept-Language: en-us, en, de, fr, ru, el, zh MIME-Version: 1.0 Newsgroups: comp.os.msdos.djgpp Subject: Re: integer overflow References: <3F246120 DOT 63C3753C AT worldnet DOT att DOT net> In-Reply-To: <3F246120.63C3753C@worldnet.att.net> Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Lines: 26 Message-ID: Date: Mon, 28 Jul 2003 00:28:41 GMT NNTP-Posting-Host: 65.148.4.157 X-Complaints-To: abuse AT earthlink DOT net X-Trace: newsread1.news.atl.earthlink.net 1059352121 65.148.4.157 (Sun, 27 Jul 2003 17:28:41 PDT) NNTP-Posting-Date: Sun, 27 Jul 2003 17:28:41 PDT Organization: EarthLink Inc. -- http://www.EarthLink.net To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Reply-To: djgpp AT delorie DOT com Paul Cousoulis wrote: > Why does this code result in an integer overflow? > > unsigned long res; > > res = (1<<31)-1; Because (1 << 31) is a signed expression. Never use signed integers for bit twiddling. Here's an example without such overflow. #include int main(void) { unsigned long res; res = 1LU << 31; printf("1LU << 31 : %lu\n", res); res = (1LU << 31)-1; printf("(1LU << 31)-1 : %lu\n", res); return 0; } 1LU << 31 : 2147483648 (1LU << 31)-1 : 2147483647