Const correctness for value parameters

前端 未结 6 881
野性不改
野性不改 2020-11-28 12:09

I know there are few question about const correctness where it is stated that the declaration of a function and its definition do not need to agree for value parameters. Thi

6条回答
  •  醉话见心
    2020-11-28 12:35

    I've read many times that making value parameters in a function const is a bad thing to do because it's unnecessary.

    However, I find it occasionally helpful to me as a check that my implementation doesn't do something I don't intend (as in the example at the end of your question).

    So, while it may not add value to the caller, it does sometimes add a small bit of value to me as an implementer, and it doesn't take anything away from the caller. So I see no harm using it.

    For example, I may be implementing a C function that takes a couple pointers to a buffer - a pointer to the start, and a pointer to the end. I'm going to put data in the buffer, but want to ensure that I don't overrun the end. So inside the function there's code that will increment a pointer as I'm adding data to it. Making the pointer to the end of the buffer a const parameter will ensure that I don't code up a bug that accidentally increments the end boundary pointer instead of the pointer I really should be incrementing.

    So a fillArray function with a signature like this:

    size_t fillArray( data_t* pStart, data_t* const pEnd);
    

    will prevent me from accidentally incrementing pEnd when I really mean to increment pStart. It's not a huge thing, but I'm pretty sure everyone who has programmed for any period of time in C has run across such a bug.

提交回复
热议问题