• Post Reply Bookmark Topic Watch Topic
  • New Topic

compile time constant expression  RSS feed

 
Sawan Mishra
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone.


conditional expression in for loop is a compile time expression
so return in line9 will never get executed but compiler couldn't catch it
and program compiles successfully why???
In case of if also similar thing happens.
please explain reason for both...


thnks in advance.
 
Ramesh Pramuditha Rathnayake
Ranch Hand
Posts: 178
2
Java MySQL Database Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The condition is checked compile time, but the value of the variable is not checked. That means, though you initialize the int with 1, compiler don't know whether the value of the variable. So there is only a possibility to run that code.
But the value of final variables are known by the compiler. So you get an error here.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ramesh Pramuditha Rathnayake wrote:The condition is checked compile time, but the value of the variable is not checked. . . .
There is a good reason for that. Imagine how difficult it would be to write a compiler which can predict the runtime value of a variable
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sawan Mishra wrote:so return in line9 will never get executed but compiler couldn't catch it
and program compiles successfully why???

Simply put: Because the compiler doesn't check the body of the loop to see what might happen to i (although I believe there are a few exceptions to that rule).

Question for you: Would you want to have to write such a compiler? And if so, how would you go about it?

It could certainly be done on a limited basis, but only at the expense of a lot of stuff that really isn't the business of a compiler. Don't forget that a compiler is basically a syntax checker, not a checker for "well-formed" logic.

There are tools around checking if you're doing "anything stupid", but they're MUCH more involved than what the compiler does.

HIH

Winston
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Winston Gutkowski wrote: . . . Would you want to have to write such a compiler? And if so, how would you go about it? . . .
And if you ever get it to work, will you live long enough to see it compile a large application ?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!