Search code examples
cconstantsreturn-type

What does returning a const do in C?


There is a similar question about C++ but it doesn't quite seem to apply here in C. I'm making a function to calculate octal tree intersections, and I made the arguments const. However, sometimes one of the arguments is returned directly, and so the compile asks that I add the const qualifier to the return type...

But what does that even achieve ? My function can definitely guarantee that it won't touch its arguments, but what does it even mean that it won't touch its return value ? Of course it won't touch it, it's been returned ! The function is over by the time this would ever matter... I must be missing something.

Here is the code (there shouldn't be any bugs, but there very well could 😅) :

/* WARNING : K >= 8 is presumed, else this is a guaranteed segfault */
const ktree *intersection( const ktree *v1, const ktree *v2 ) {
    const enum content r1 = root( v1 );
    const enum content r2 = root( v2 );

    if ( content_empty == r1 || content_empty == r2 ) {
        return ktree_leaf( content_empty );
    } else if ( content_full == r1 ) {
        return v2;
    } else if ( content_full == r2 ) {
        return v1;
    }
    return new_ktree(
        content_partial,
        intersection( kchild( 0, v1 ), kchild( 0, v2 ) ),
        intersection( kchild( 1, v1 ), kchild( 1, v2 ) ),
        intersection( kchild( 2, v1 ), kchild( 2, v2 ) ),
        intersection( kchild( 3, v1 ), kchild( 3, v2 ) ),
        intersection( kchild( 4, v1 ), kchild( 4, v2 ) ),
        intersection( kchild( 5, v1 ), kchild( 5, v2 ) ),
        intersection( kchild( 6, v1 ), kchild( 6, v2 ) ),
        intersection( kchild( 7, v1 ), kchild( 7, v2 ) )
    );
}

( I have chosen not to include all the tree functions as I think having the code actually work is irrelevant to the question. I can provide them if there is a good reason I didn't think of, though )


Solution

  • It is not the return value that is const. Instead, your function returns a non-const pointer, but it points to a const object.

    The compiler is right, as you return v1 or v2, the data type of the returned value needs to be const ktree *.

    If you wanted the pointer to be const, you would write ktree * const intersection(.... But in C the const type qualifier is ignored on function return types, they make no sense.

    However, you can decide at the caller to make the pointer const that stores the returned:

        /* ... */
        const ktree * const v = intersection(t1, t2);
        /* ... */