开发者

Is 2+3 considered as a literal?

开发者 https://www.devze.com 2022-12-29 13:49 出处:网络
Suppose i have something like int x = 2 + 3; Is x cons开发者_开发知识库idered to be a literal?x is a symbol. 2 + 3 is an expression. 2 and 3 are literals.No, it\'s two literals in a compile-time co

Suppose i have something like

int x = 2 + 3;

Is x cons开发者_开发知识库idered to be a literal?


x is a symbol. 2 + 3 is an expression. 2 and 3 are literals.


No, it's two literals in a compile-time constant expression. Depending on how it gets compiled, you may not be able to tell the difference in the resulting binary.


  • int - type of the variable, identifier
  • x - name of the variable, identifier
  • = - assignment
  • 2 - literal
  • + - operation between two literals
  • 3 - literal
  • ; - end of the statement


  • int is a type
  • x is an identifier
  • =,+ are operators
  • 2,3 are literals as "StringLiteral" would be

To learn how all these syntacically elements are named you could browse i.g.

http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html

http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html


yeah it is a literal. the expression will be reduced to literal, i.e. even before the program is run, so it is literal

other types of literal you might see in real-world (the programmer can't be bothered too compute it by himself, let the compiler do the grunt work of determining the literal):

const unsigned int NEGATIVE_TESTER_FOR_32_BIT = 1 << 31;

const char ALPHABET_PIVOT = 'A' + ( ('Z' - 'A') / 2);

[EDIT: regarding depending on the compiler] yeah it depends on the compiler. but i guess most of compiler writers do their homework, if they can generate the necessarily assembly or virtual machine instruction of the language, computing things in compile time is just a walk in the park for them. in fact, even the character literal 'H' for example, doesn't even get stored in file as verbatim 'H', it gets stored as number literal (72, or in hex view 0x48 or 48h) in final machine code. i can hazard a guess that all compilers will reduce the two literals to a literal, not expression. it's a walk in the park for them(compiler writers)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号