为什么连续分号的代码会编译? [英] Why does code with successive semi-colons compile?

查看:104
本文介绍了为什么连续分号的代码会编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据我的科学Java实验, int x = 0; 相当于 int x = 0 ;; 相当于 int x = 0 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; >

  • 为什么Java允许这样做?它有任何实际应用吗?

  • 这些只是空的陈述吗?他们实际上是否在运行时占用了额外的处理时间? (我会假设它们已经过优化了吗?)

  • 其他语言是否可以这样做?我猜它是从C继承的东西,就像Java中的很多东西一样。这是真的吗?


  • 解决方案

    正如Jake King所写,你可以制作空的陈述,什么都不做循环中:

      while(condition); 

    但要明白,你会写

      while(condition)
    ;

    甚至更好:

      while(条件)
    / **故意为空* /
    ;

    甚至更好,正如MichaelKjörling在评论中指出的那样,

      while(条件)
    {
    / **故意空* /
    }

    更常见的是,你会在无限循环的for语句中看到它:

      for(;;)

    或只有一个空语句

      for(start ;;)
    for(; cond;)
    for(;; end)

    你可以做的另一件事是,编写一个程序,一个用一个,一个用2个分号:

     公共类空
    {
    public static void main(String args [])
    {
    System.out.println(Just semicolons);;
    }
    }

    编译它,并运行list字节代码的大小(identic)并在字节码上执行md5sum(identic)。



    因此,在没有改变语义的情况下,它显然已经被优化了,至少对于1.6-Oracle编译器我可以这么说。


    According to my scientific Java experimentation, int x = 0; is equivalent to int x = 0;; which is equivalent to int x = 0;;;;;;;;;;;;;;;

    1. Why does Java allow for this? Does it have any practical application?
    2. Are each of these just empty statements? Do they actually take up any extra processing time during runtime? (I would assume they're just optimized out?)
    3. Do other languages do this? I'm guessing it's something inherited from C, like a lot of things in Java. Is this true?

    解决方案

    As Jake King writes, you can produce empty statements to do nothing in a loop:

    while (condition);
    

    but to make it obvious, you would write

    while (condition)
        ;
    

    or even better:

    while (condition)
    /** intentionally empty */
        ;
    

    or even better, as Michael Kjörling pointed out in the comment,

    while (condition)
    {
        /** intentionally empty */
    }
    

    More often, you see it in for-statements for endless loops:

    for (;;)
    

    or only one empty statement

    for (start;;) 
    for (;cond;) 
    for (;;end) 
    

    Another thing you can do, is, to write a program, once with one, and once with 2 semicolons:

    public class Empty
    {
        public static void main (String args[])
        {
            System.out.println ("Just semicolons");;
        }
    }
    

    Compile it, and run list the size of byte code (identic) and do an md5sum on the bytecode (identic).

    So in cases, where the semantics aren't changed, it is clearly optimized away, at least for the 1.6-Oracle compiler I can say so.

    这篇关于为什么连续分号的代码会编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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