Software Engineering for Smart Data Analytics & Smart Data Analytics for Software Engineering

User Tools

Site Tools

Bug JT_Cor_070 (Comparison of int with long beyond int range)

Inspired by

INT: Bad comparison of int value with long constant (INT_BAD_COMPARISON_WITH_INT_VALUE)

Original Description

This code compares an int value with a long constant that is outside the range of values that can be represented as an int value. This comparison is vacuous and possibly incorrect.

Detailed Description

By default, the int data type is a 32-bit signed two's complement integer, whereas the long data type is a 64-bit two's complement integer. Therefore a comparison of an int to a long constant that cannot be represented in 32 bits is always false and thus useless. The occurrence of such code indicates that the programmer did not really understand what (s)he was doing.

Sample Problem Scenario

<code Java> public void compareIntToLong(int i) {

  long j = Long.MAX_VALUE;
  if(i == j){
       System.out.println("True");  // This branch is never reached.
  else {
       System.out.println("False"); // This branch is always taken.

} </Code>

Sample Counter Scenario

Here is a minimal example where the problem DOES NOT occur. Hence this should not be reported by your detector. Use this code too for testing your analysis:<code Java> public void compareIntToLong(int i) {

  long j = 1234567890;
  if(i == j){
  else {

} </Code>

Sample Fix

No way to automatically fix this. The programmer must inspect himself his code to understand the implications of what he did.

teaching/labs/mdse/2013/bug_descriptions/jt-bug-cor70.txt · Last modified: 2018/05/09 01:59 (external edit)

SEWiki, © 2023