The Benefits of Constants

前端 未结 14 1875
南笙
南笙 2021-02-04 07:46

I understand one of the big deals about constants is that you don\'t have to go through and update code where that constant is used all over the place. Thats great, but let\'s s

14条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-04 08:10

    If you declare a variable to be a constant, then the optimizer can often eliminate it via 'constant folding' and thus both speed up your program and save you space. As an example, consider this:

    var int a = 5;
    const int b = 7;
    ...
    c = process(a*b);
    

    The compiler will end up creating an instruction to multiply a by 7, and pass that to 'process', storing the results in c. However in this case:

    const int a = 5;
    const int b = 7;
    ...
    c = process(a*b);
    

    The compiler will simply pass 35 to process, and not even code the multiply. In addition, if the compiler knows that process has no side effects (ie, is a simple calculation) then it won't even call process. It will just set c to be the return value of process(35), saving you a function call.

提交回复
热议问题