The Benefits of Constants

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

    Marking a variable as constant declares your intent as a programmer that this will be a consistent value whenever it's accessed during the execution of the code. Consider it a form of documentation that also causes the compiler to enfore your design.

    0 讨论(0)
  • 2021-02-04 08:29

    This isn't really an Ada-specific question.

    The general benifits of constants over variables:

    • Prevents code errors from "constant" accidentally getting modified.
    • Informs the compiler that it can assume the value will not change when optimizing.

    Ada specific benifits:

    • For numeric constants, you don't have to specify a type (named numbers). If you declare it this way, it will be usable in any expression for that kind of number. If you use a variable instead, it can only be used in expressions of that variable's exact type.

    Example:

    Seconds_Per_Minute : constant := 60;
    Secs_Per_Min       : Integer  := 60;
    
    type Seconds_Offset is 0 .. Integer'last; --'
    
    Min1, Secs1 : Integer;
    Min2, Secs2 : Seconds_Offset;
    
    ...
    --// Using the named number, both of these compile no problem.
    Secs1 := Min1 * Seconds_Per_Minute;
    Secs2 :=  Min2 * Seconds_Per_Minute;
    
    --// The second line here gives an error, since Integer is a 
    --// different type than Seconds_Offset.
    Secs1 := Min1 * Secs_Per_Min;
    Secs2 := Min2 * Secs_Per_Min;
    
    0 讨论(0)
提交回复
热议问题