🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: gnu.gcc.bug
Article #2688

C code optimization (suggestion, not a bug)

#2688
From: WILCOX
Date: Sat, 27 May 1989 20:34
29 lines
1249 bytes
Assuming that the target machine implements two's compliment arithmetic
and doesn't have store condition code instructions, there is a simple
optimization that few C compilers seem to use.  Given:

     int a;
     int b, c;
     a = (b < c);

the usual approach is something like:

     a = 0;
     if( ! (b < c)) goto label;
     a = 1;
label:

A better approach would seem to be:

a = (unsigned)((c - b) >> (WIDTH_OF_INT_IN_BITS - 1));

In other words, subtract rather than compare, and shift the resulting sign
bit into the least-significant bit position with zero extend.  There is
also a variation using signed rather than unsigned shift, which generates
either -1 or 0, followed by an increment to produce either 0 or 1.

     --Dwight Wilcox
       Code 412
       Naval Ocean Systems Center
       San Diego, CA  92152-5000
Technical Details
Message-ID: <8905272035.AA28102@life.ai.mit.edu>
Path: arc1-ca.pugleaf.net!utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!NOSC-TECR.ARPA!WILCOX

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!NOSC-TECR.ARPA!WILCOX
From: WILCOX@NOSC-TECR.ARPA
Newsgroups: gnu.gcc.bug
Subject: C code optimization (suggestion, not a bug)
Message-ID: <8905272035.AA28102@life.ai.mit.edu>
Date: 27 May 89 20:34:27 GMT
Sender: daemon@tut.cis.ohio-state.edu
Distribution: gnu
Organization: GNUs Not Usenet
Lines: 29