Use of 'const' for function parameters

前端 未结 30 2707
借酒劲吻你
借酒劲吻你 2020-11-22 03:06

How far do you go with const? Do you just make functions const when necessary or do you go the whole hog and use it everywhere? For example, imag

30条回答
  •  有刺的猬
    2020-11-22 03:27

    Marking value parameters 'const' is definitely a subjective thing.

    However I actually prefer to mark value parameters const, just like in your example.

    void func(const int n, const long l) { /* ... */ }
    

    The value to me is in clearly indicating that the function parameter values are never changed by the function. They will have the same value at the beginning as at the end. For me, it is part of keeping to a very functional programming sort of style.

    For a short function, it's arguably a waste of time/space to have the 'const' there, since it's usually pretty obvious that the arguments aren't modified by the function.

    However for a larger function, its a form of implementation documentation, and it is enforced by the compiler.

    I can be sure if I make some computation with 'n' and 'l', I can refactor/move that computation without fear of getting a different result because I missed a place where one or both is changed.

    Since it is an implementation detail, you don't need to declare the value parameters const in the header, just like you don't need to declare the function parameters with the same names as the implementation uses.

提交回复
热议问题