为什么Java中没有字节或短文字? [英] Why are there no byte or short literals in Java?

查看:133
本文介绍了为什么Java中没有字节或短文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过在值上附加L来创建文字长度;为什么我不能以某种类似的方式创建文字短或字节?为什么我需要使用带有强制转换的int文字?

I can create a literal long by appending an L to the value; why can't I create a literal short or byte in some similar way? Why do I need to use an int literal with a cast?

如果答案是因为C中没有短文字,那为什么没有短文C中的文字?

And if the answer is "Because there was no short literal in C", then why are there no short literals in C?

这实际上并没有以任何有意义的方式影响我的生活;写(短)0而不是0S或其他东西很容易。但这种不一致让我很好奇;这是你晚上睡觉时困扰你的事情之一。有人在某个时候做出了一个设计决定,可以为某些原始类型输入文字,但不能为所有原始类型输入文字。为什么?

This doesn't actually affect my life in any meaningful way; it's easy enough to write (short) 0 instead of 0S or something. But the inconsistency makes me curious; it's one of those things that bother you when you're up late at night. Someone at some point made a design decision to make it possible to enter literals for some of the primitive types, but not for all of them. Why?

推荐答案

在C中, int 至少应该有CPU的自然字大小和 long 可能意味着更大的自然字大小(在最后一部分不确定,但它也可以解释为什么 int long 在x86上具有相同的大小。)

In C, int at least was meant to have the "natural" word size of the CPU and long was probably meant to be the "larger natural" word size (not sure in that last part, but it would also explain why int and long have the same size on x86).

现在,我的猜测是:对于 int long ,有一个完全适合机器寄存器的自然表示。但是,在大多数CPU上,较小的类型 byte short 必须填充到 int 无论如何在使用之前。如果是这种情况,你也可以进行演员表。

Now, my guess is: for int and long, there's a natural representation that fits exactly into the machine's registers. On most CPUs however, the smaller types byte and short would have to be padded to an int anyway before being used. If that's the case, you can as well have a cast.

这篇关于为什么Java中没有字节或短文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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