• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

if statement dont let you declare a variable without {}

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
why is that?
its not allowed

but its allowed

is it because compiler need to clear about scope of variable?
 
Bartender
Posts: 4568
9
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's related to scope, yes. What would be the point of allowing the first version? Without brackets, the if statement just refers to the "block" up to the next semi-colon. Which means that you're declaring a variable which has the scope of this line only - which means it's useless as it can't be used anywhere. That must be a mistake, so the compiler prevents you from doing it.
 
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The if-then and if-then-else Statements says -


In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement:

void applyBrakes(){
if (isMoving) currentSpeed--; // same as above, but without braces
}

Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.



Regards,
Dan
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic