This is the mail archive of the gcc-prs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

c++/7536: C++ front end does not warn of promotion of negative ints to unsigneds


>Number:         7536
>Category:       c++
>Synopsis:       C++ front end does not warn of promotion of negative ints to unsigneds
>Confidential:   no
>Severity:       non-critical
>Priority:       low
>Responsible:    unassigned
>State:          open
>Class:          sw-bug
>Submitter-Id:   net
>Arrival-Date:   Thu Aug 08 01:56:01 PDT 2002
>Closed-Date:
>Last-Modified:
>Originator:     jss@ast.cam.ac.uk
>Release:        gcc-3.1
>Organization:
>Environment:
gcc-3.1 (RedHat RPM 3.1-1), on RedHat Linux 7.3 on an AMD Athlon (compiling for i386)
>Description:
An expression int+unsigned or int-unsigned promotes the int variable to an unsigned before doing the operation. Quite often this can do the /wrong/ thing, just like comparisons of ints and unsigneds. g++ should warn for obvious mistakes (as the c front end does), and should optionally warn for less obvious mistakes.

e.g.

unsigned a = 15;
double b = -30 - a;

should issue a warning, as b ends up at around 2^32, and probably not the expected -15.

Further possibilities for warning are:

unsigned a = 15;
int b = -30;
double c = b-c

(the same thing).

Another possibility is for warning for every implicit int/unsigned arithmetic operation/promotion, as the int could be negative. For instance:

double dostuff(int i)
{
  const unsigned cx = 10;
  return i-cx;
}

int main()
{
  dostuff(-10);  // dangerous
  return 0;
}

This can hide a serious error. However many programs will give lots of warnings. Maybe this could go into -Wconversion?

The operation int+unsigned usually works (due to twos-complement representation - is this part of the standard?), however things like

int a = -10;
unsigned b = 20;
double c = b + a;

should also be flagged if the operation relies on non-defined behaviour.

I'll include a test-case for warnings.
>How-To-Repeat:
Compile above with
g++ -W -Wall -Wconversions -O2 test.cc
>Fix:

>Release-Note:
>Audit-Trail:
>Unformatted:
----gnatsweb-attachment----
Content-Type: application/octet-stream; name="test.cc"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="test.cc"

I2luY2x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