简体   繁体   中英

Constant expressions in Objective-C

If you have "128 + 7 – i" (where i is declared 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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM