JavaScript is not currently enabled, but is required for full CodeSonar manual search and browse functionality.
If you are viewing this file in your hub's Web GUI, enable JavaScript in your browser: you will also need it for GUI functionality.
If you opened this file directly from disk, your browser may be directly suppressing JavaScript functionality: certain browsers perform this suppression on local files (but not files delivered by web servers) for security reasons.
| CodeSonar® 9.0p0 Hot Tips | CONFIDENTIAL | CodeSecure Inc |
The result of an integer computation that might overflow is cast into long, with possible loss of precision.
Floating point operations are by nature approximated. This can introduce bugs when precise, mathematical properties are expected from inherently imprecise floating point computations. Moreover, computations that might lose precision or overflow, whose result is stored in a larger type, are suspicious since, by computing on the larger type from the beginning, one could avoid approximations and overflows.
| クラス名 | Cast: int Computation to long (Java) | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| 日本語クラス名 | Cast: int Computation to long (Java) | |||||||||
| クラス分類 | 信頼性 (reliability) | |||||||||
| ニーモニック | JAVA.ARITH.OFLOW | |||||||||
| カテゴリー |
|
|||||||||
| 対応言語 | Java で利用可能です。 |
|||||||||
| 有効/無効設定 | このワーニングクラスのチェックはデフォルトで有効になっています。チェックを無効にするにはプロジェクト設定ファイル
(configuration file)に以下の WARNING_FILTER ルールを追加してください。
WARNING_FILTER += discard class="Cast: int Computation to long (Java)" |
public class MillisecondsInDays {
public static void main(String[] args) {
int days = Integer.parseInt(args[0]);
long milliseconds = days * 24 * 60 * 60 * 1000; // "Cast: int Computation to long (Java)" warning issued here
System.out.printf("Inside %d days there are %d milliseconds", days, milliseconds);
}
}
The computation days * 24 * 60 * 60 * 1000 is performed on integers and then stored into a long. As a consequence, the extra space allowed by a long value is not exploited and the computation will overflow if days is larger than 24.
To avoid this problem, perform the computation with long values, so that the entire long space is available. Overflow will only occur for very large values of days.
public class MillisecondsInDays {
public static void main(String[] args) {
int days = Integer.parseInt(args[0]);
long milliseconds = days * 24L * 60 * 60 * 1000;
System.out.printf("Inside %d days there are %d milliseconds", days, milliseconds);
}
}
If a large type for the result of a computation is desired, compute from the beginning on that type instead of applying a type conversion at the end of the computation.
設定ファイルの以下のパラメータがこのワーニングクラスのチェックに影響します。