为什么int i = 1024 * 1024 * 1024 * 1024编译没有错误? [英] Why does int i = 1024 * 1024 * 1024 * 1024 compile without error?

查看:677
本文介绍了为什么int i = 1024 * 1024 * 1024 * 1024编译没有错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int 的限制是从-2147483648到2147483647.。

The limit of int is from -2147483648 to 2147483647.

如果我输入

int i = 2147483648;

然后Eclipse将在2147483648下面提示红色下划线。

then Eclipse will prompt a red underline under "2147483648".

但如果我这样做:

int i = 1024 * 1024 * 1024 * 1024;

它将编译正常。

public class Test {
    public static void main(String[] args) {        

        int i = 2147483648;                   // error
        int j = 1024 * 1024 * 1024 * 1024;    // no error

    }
}

也许这是一个Java中的基本问题,但我不知道为什么第二个变量不会产生错误。

Maybe it's a basic question in Java, but I have no idea why the second variant produces no error.

推荐答案

该语句没有错;你只是将4个数字相乘并将其分配给一个int,恰好就是溢出。这与分配单个文字不同,后者将在编译时进行边界检查。

There's nothing wrong with that statement; you're just multiplying 4 numbers and assigning it to an int, there just happens to be an overflow. This is different than assigning a single literal, which would be bounds-checked at compile-time.

这是超出范围的导致错误的 literal ,而不是赋值

It is the out-of-bounds literal that causes the error, not the assignment:

System.out.println(2147483648);        // error
System.out.println(2147483647 + 1);    // no error

相比之下 long literal编译正常:

By contrast a long literal would compile fine:

System.out.println(2147483648L);       // no error

注意,事实上,结果仍然是在编译时计算,因为 1024 * 1024 * 1024 * 1024 常驻表达

Note that, in fact, the result is still computed at compile-time because 1024 * 1024 * 1024 * 1024 is a constant expression:

int i = 1024 * 1024 * 1024 * 1024;

变为:

   0: iconst_0      
   1: istore_1      

注意结果(<只需加载并存储code> 0 ),不会发生乘法。

Notice that the result (0) is simply loaded and stored, and no multiplication takes place.

来自JLS§3.10.1 (感谢@ChrisK在评论中提出它):

From JLS §3.10.1 (thanks to @ChrisK for bringing it up in the comments):


如果是十进制文字则是编译时错误类型 int 大于 2147483648 (2 31 ),或者如果是小数字 2147483648 出现在除一元减号运算符的操作数之外的任何地方(§15.15.4

It is a compile-time error if a decimal literal of type int is larger than 2147483648 (231), or if the decimal literal 2147483648 appears anywhere other than as the operand of the unary minus operator (§15.15.4).

这篇关于为什么int i = 1024 * 1024 * 1024 * 1024编译没有错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆