int* const* foo(int x); is a valid C function prototype. How do you "read" this return type?

234 views Asked by At

I notice that this is a valid prototype while reading through the ANSI C grammar spec from 1985 published by Jeff Lee and I compiled a function with this signature. What exactly might a function with this prototype return? What would a simple body of this function look like?

2

There are 2 answers

2
vsoftco On BEST ANSWER

The return type is a pointer to const pointer to int. Read the declaration from right to left, and it will make things much easier. My favourite tutorial for complicated pointer declarations: http://c-faq.com/decl/spiral.anderson.html

Some (quite artificial) example:

#include <iostream>

int* const * foo(int x)
{
    static int* const p = new int[x]; // const pointer to array of x ints
    for(int i = 0; i < x ; ++i) // initialize it with some values
        p[i] = i; 
    return &p; // return its address
}

int main()
{
    int* const* p = foo(10); // our pointer to const pointer to int
    //*p = nullptr; // illegal, cannot modify the dereferenced pointer (const)
    std::cout << (*p)[8]; // display the 8-th element
}
0
Sam Varshavchik On

foo is a function that takes an int parameter and returns a pointer to a const pointer to an int.