Could the return cast (==>) give place to an undefined behavior? the idea of the code is very simple, iterate through an intrusive list (plist) and return the element if found.
Could the return cast (==>) give place to an undefined behavior?
No. casting a (my_custom_type_t*)
to (const my_custom_type_t*)
does not cause UB.
Neither does either of the below cause UB
const my_custom_type_t* plist1;
const my_custom_type_t* obj1 = get_object_by_id(plist1, "x");
printf("%d\n", obj1->some_field);
my_custom_type_t* plist2;
my_custom_type_t* obj2 = get_object_by_id(plist2, "x");
obj2->some_field = 2;
Yet the following does invoke UB ...
const my_custom_type_t* plist3;
my_custom_type_t* obj3 = get_object_by_id(plist3, "x");
// UB
obj3->some_field = 3;
To avoid this potential, write 2 functions, one being a wrapper of the other.
static const my_custom_type_t* get_object_by_id_const(
const my_custom_type_t* plist, const char *my_id) {
// as above in OP's post
return obj;
}
static my_custom_type_t* get_object_by_id_noconst(
my_custom_type_t* plist, const char *my_id) {
const my_custom_type_t* obj = get_object_by_id_const(plist, my_id);
return (my_custom_type_t*) obj;
}