static const vs #define

前端 未结 11 877
醉话见心
醉话见心 2020-11-22 13:01

Is it better to use static const vars than #define preprocessor? Or maybe it depends on the context?

What are advantages/disadvantages for

11条回答
  •  盖世英雄少女心
    2020-11-22 13:34

    As a rather old and rusty C programmer who never quite made it fully to C++ because other things came along and is now hacking along getting to grips with Arduino my view is simple.

    #define is a compiler pre processor directive and should be used as such, for conditional compilation etc.. E.g. where low level code needs to define some possible alternative data structures for portability to specif hardware. It can produce inconsistent results depending on the order your modules are compiled and linked. If you need something to be global in scope then define it properly as such.

    const and (static const) should always be used to name static values or strings. They are typed and safe and the debugger can work fully with them.

    enums have always confused me, so I have managed to avoid them.

提交回复
热议问题