The Benefits of Constants

前端 未结 14 1848
南笙
南笙 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:24

    It's possible that the compiler could reduce code size .. for example, in package System you'll find (on an x86 machine)

    type Bit_Order is (High_Order_First, Low_Order_First);
    Default_Bit_Order : constant Bit_Order := Low_Order_First;
    

    so that given

    case System.Default_Bit_Order is
       when System.High_Order_First =>
          --  Big-endian processing
       when System.Low_Order_First =>
          --  Little-endian processing
    end case;
    

    the compiler can completely eliminate the 'wrong' branch while your code retains its portability. With GNAT you need to use non-default optimisation for this to happen: -O2 I think.

    Both branches have to be compilable -- this is an optimisation, not #ifdef processing.

提交回复
热议问题