4 ms·
> a function which finds an integer in an array "should" get that array as a "const int ". But if the caller wants to modify the found element, it needs to do u
by pif 9y ago
> a function which finds an integer in an array "should" get that array as a "const int ". But if the caller wants to modify the found element, it needs to do ugly casting (really bad practice).
My friend, your example is wrong! The caller can happily work with a mutable array; the function accepting a "const" pointer is just a guarantee that the function itself* won't modify the content.
size_t look4 (const int *ptr, int val);
void caller (int *ptr, int old_val, int new_val)
{
size_t index = look4(ptr, old_val);
ptr[index] = new_val;
}
- pjmlp 9y agoI know you are just giving an example, but caller() should check that what came from look4() is a valid index into ptr.
- deleted 9y ago[deleted]
- jjnoakes 9y agoSure, if you return an index. I bet the parent poster was discussing returning a pointer, though. Imagine look4 returned a pointer to the found element. Making look4's signature const-correct in C is not possible. (Think of strchr).
- jstimpfle 9y agoAs my sibling poster explained, that's not why meant. Try to reduce some of the problems these people have: https://stackoverflow.com/questions/856542/elegant-solution-to-duplicate-const-and-non-const-getters https://stackoverflow.com/questions/856542/elegant-solution-...