Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obscure pointer declaration

Tags:

c++

c

I have a question which is in some way, I guess, completely trivial: what's that (and why)?

const float *(*const*)(int)

My understanding is that it is a "pointer to a constant pointer to a function taking an int as argument and returning a pointer to constant float".

Is it correct ?

How to "mentally parse" (*const*) ? Especially as there is no name, at first I didn't know where to start. I think that the only possibility for a "name" would be to put it like that: *const *name as other combination are invalid (if I am correct), so then "name is a pointer to a constant pointer ...".

Is this reasoning valid ?

Thanks !

like image 759
Cedric H. Avatar asked Sep 21 '10 21:09

Cedric H.


2 Answers

You are correct that name goes after *const*. If you plug the line const float *(*const* name)(int) in cdecl.org, it will tell you that it means "declare name as pointer to const pointer to function (int) returning pointer to const float"

As for mental parsing, I just remember that R (*p)(A) is a pointer to function. Therefore R (**p)(A) is a pointer to pointer to function, and all it takes at this point is to remember how const and * interact.

like image 131
Cubbi Avatar answered Oct 18 '22 09:10

Cubbi


Yes that reasoning is valid. Put it on the right of all '*'es that are not within function parameter lists and on the left of all []'es that are not in function parameter lists. Then you have

const float *(*const* name)(int)

Then read it as usual. From thereon and even how to find the correct place for the name, there are many tutorials how to parse this on the internet.

For C++, you may want to look into geordi.

< litb> geordi: -c int name;
< geordi> Success
< litb> geordi: make name a const float *(*const*)(int) and show
< geordi> -c float const *(*const* name)(int) ;
< litb> geordi: << TYPE_DESC(const float *(*const*)(int))
< geordi> pointer to a constant pointer to a function taking an integer 
          and returning a pointer to a constant float

You can then do analysis on the syntax of it

< litb> geordi: show parameter-declaration and first decl-specifier-seq
< geordi> `int` and `float const`.
< litb> geordi: make name an array of 2 pointer to function taking int and 
        returning pointer to float and show
< geordi> -c float const *(* name[2])(int );

It lets you mix C with English

< litb> geordi: make name an array of 2 pointer to (float const*(int)) and show
< geordi> -c const float *(* name[2])(int);

As you see, it's pretty powerful.

like image 37
Johannes Schaub - litb Avatar answered Oct 18 '22 09:10

Johannes Schaub - litb