Re:Elevate your C programming skills by exploring the SQLite...
by pif on Sunday July 09, 2017 @10:53AM
(#14729974)
> 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;
}
Re:Elevate your C programming skills by exploring the SQLite...
by jjnoakes on Sunday July 09, 2017 @02:25PM
(#14730982)
Sure, 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).
Re:Elevate your C programming skills by exploring the SQLite...
by jstimpfle on Sunday July 09, 2017 @03:55PM
(#14731352)
As 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-...
An example from the top of my head, 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).
Similar problems exist in most other programming languages. Most have only "shallow" const. You can mark an Java array member as final, but you can't disallow mutations to that array.
Const-correctness is similar to types - it breaks very quickly, and when it breaks it gets in the way.
That means I resort to indices when possible. When pointers are needed I typically avoid const.