Search code examples
cmisraansi-c

can I require a return value to be a pointer to a constant


say I have two 'modules'. For instance the hardware-interface layer of a RS-232 port and a layer above it to make it more abstract.

I have a receive buffer like this: U8BIT myBuffer[MAX]. U8BIT is typedeffed: typedef unsigned char

There are however two type of messages that can be received. One that has a header and another one that doesn't have a header. The logic for this is already written.

The 'layer above' will access this buffer but it should have no knowledge whether this is a header or header-less message.

Thus I have a function like this:

U8BIT * fooBuffer(U8BIT * maxLength)
{
    U8BIT * retval;
    if( isHeaderless() )
    {
        retval = &(myBuffer[0]);
        *maxLength = MAX;
    }
    else
    {
        retval = &(myBuffer[5]);
        *maxLength = MAX - 5;
    }
    return retval;
}

How can I make sure that any function calling this function is not able to alter the contents of the returned pointer?

Yes I know it will always be possible. And not trying to make it harder for others to do try to modify it. I want it to be 'not possible' so that it will be less easier to make mistakes because the compiler will complain if you do try to modify a const.

Can I just declare the function as follows: const U8BIT * fooBuffer(U8BIT * maxLength)


Solution

  • Use const U8BIT * as the return type of the function.

    For example in your function:

    const U8BIT * fooBuffer(U8BIT * maxLength)
    {
        U8BIT * retval;  
    
        // code
    
        return (const U8BIT *) retval;
    } 
    

    If retvalpointer is not dereferenced inside your fooBuffer function, declare it also as const U8BIT * and then the cast in the return statement is no longer needed.