herozem
V2EX  ›  C

<<程序设计实践>>, 有一个问题想问一下

  •  
  •   herozem · Jan 4, 2015 · 1431 views
    This topic created in 4170 days ago, the information mentioned may be changed or developed.

    我看的这一节是1.5, 主题是Magic Numbers, 大致意思是尽量不要在代码中使用含义不明的数字, 应该要给他们取个名字; define numbers as constants, not macros;

    那么问题来了:

    Exercise 1-10. How would you rewrite these definitions to minimize opotential errors?
    
    #define FT2METER 0.3048
    #define MI2FT 5280.0
    ...
    

    在C++中可以用const定义, 在Java中可以用final float定义, 在C中, enum只能用于整数,define又是不被推荐的, 那么有别的方法吗?

    ps: 1.5节中有一句话我没看懂, 不知道大家可以给我讲讲么:(白乔 注解版Page 27, 中间一段)It may not be worth inventing a name for the size of a local array, but it is definitely worth writing code that does not have to change if the size or type changes.

    6 replies    2015-01-05 16:46:05 +08:00
    saber000
        1
    saber000  
       Jan 5, 2015
    double FT2METER = 0.3048; // 敢改切JJ
    double MI2FT = 5280.0; // 改了捅菊花
    herozem
        2
    herozem  
    OP
       Jan 5, 2015
    @saber000 不对吧, 首先,用enum和const定义常量的目的是让存储常量值的变量不能被重新肤质赋值;因为是double类型, 所以enum不可取, 后来我验证了一下, c89中是有const关键字的;-), 所以这个题应该是用const定义这些个常量
    scenix
        3
    scenix  
       Jan 5, 2015
    const
    canautumn
        4
    canautumn  
       Jan 5, 2015
    最后一句应该是说,如果只是为了给本地数组大小的数字起个名字,这么做不太值得;但是如果是考虑到当数组大小数值或类型改变时,不需要修改代码(仅需改变常量定义的值),那这么做就是值得的。
    saber000
        5
    saber000  
       Jan 5, 2015 via Android
    @herozem 我专职Python开发,Python没有const
    herozem
        6
    herozem  
    OP
       Jan 5, 2015
    @canautumn 谢谢, 应该就是这个意思 ;-)
    @saber000 嗯, python中是没有const, 但是可以hack
    @scenix 是的;-)
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3019 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 09:04 · PVG 17:04 · LAX 02:04 · JFK 05:04
    ♥ Do have faith in what you're doing.