• 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
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

chapter 3 self test, question 8

 
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The function...

void go(int ouch)
{
ouch++;
for (int ouch = 0; ouch < 5; ouch++)
{}
}

So this will compile in C++, but not Java?? Why doesn't JAVA accept this,but C++ does?
 
Ranch Hand
Posts: 67
Eclipse IDE Fedora Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

R Gle wrote:The function...

void go(int ouch)//1
{
ouch++;
for (int ouch = 0; ouch < 5; ouch++)//2
{}
}

So this will compile in C++, but not Java?? Why doesn't JAVA accept this,but C++ does?



In case of java, once ouch is declared at 1 it can't be declared again at 2 because ouch is considered local to function block/scope and for loop come under that scope. So, you can't declare same variable two times in the same block/scope.

In case of c++, I think for loop may be considered as different scope to the compiler. So, may be redeclaration is not a problem.

 
Ranch Hand
Posts: 38
Eclipse IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Variables and functions are accessed using scoping rules, not visbility rules, in C++, int ouch is decleared as function parameter and again in side the for loop,
the scope of the variable is fixed inside the braces, it is allow in C++ but not in java.
 
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic