scope of local variable in enhanced for-loop

后端 未结 5 1155
执念已碎
执念已碎 2021-01-18 02:00

I have a rather simple question about variable scope.

I am familiar with the Enhanced For-Loops but I do not get why I should declare a new variable to keep each el

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-18 02:37

    Just to have the reference here: The JLS Section 14.14.2, The enhanced for statement defines the enhanced for-loop to have the following structure (relevant for this question):

     EnhancedForStatement:
       for ( {VariableModifier} UnannType VariableDeclaratorId : Expression ) Statement 
    

    where UnannType can be summarized to be "a type" (primitive, reference...). So giving the type of the loop variable is simply obligatory according to the language specification - causing the (admittedly: somewhat confusing) observations described in the question.

提交回复
热议问题