Constant expressions in Objective-C
If you have "128 + 7 – i" (where i is decl开发者_如何转开发ared to be an integer variable), is it a constant expression? Why or why not?
This depends on where i
is declared, and whether the compiler can figure out, if there is any chance it can get changed at runtime.
For example, if your code looked like this:
...
int i = 3;
int x = 128 + 7 - i;
...
the compiler could figure out, that there is no way i
could change before it was used in your expression. In that case, it could be inlined as a constant expression at compile time.
If, however, it were like this:
-(void) doSomething:(int) i {
...
int x = 128 + 7 - i;
...
}
The value could change at runtime, depending on the method parameter, in which case it could not be constant for the compiler.
Be aware, that whether or not the compiler can do optimizations like the one described above depends on the compiler's settings. For example, in debug builds it would most certainly not do so.
EDIT: As correctly pointed out by Rudy Velthuis in the comments, I was a little too fast in my answer. In fact, the first example is not really a constant expression, which the compiler will (very explicitly indeed) tell you. I did not take into account that constant expression is a fixed term with a clear definition (e. g. see Java Language Spec here, don't have a C version handy right now). Instead I confused it with a compiler optimization technique which through data flow analysis inside a method would allow it to replace the aforementioned code with a constant value.
I'd say it's not because i is a variable, so, when you do some math with a variable, the result cant be a constant.
精彩评论