C · How To

Reading Complicated C Declarations

In this post I’ll be writing about how to easily read the complicated C declarations like


char (*(*x()) []) ()

char (* (*x[3]) ()) [5]

void (*f)(int,void (*)())

int **(*f)(int**,int**(*)(int **,int **));

Let’s go ahead with the first one

char (*(*x()) []) ()

1. Start from the variable name ——————————-x
2. Go right, find () ———————————————- is a function having no argument
3. Go left, find * ————————————and returns a pointer
4. Nothing to right, but )
5. So go left, nothing to the left but (
4. So go right, find [] ————————————– to an array
5. Go left, find * ———————————————-of pointer
6. Go right, find nothing but )
7. So go left, find nothing but (
8. so go right, find () ———————————–to a function
9. Go left, find char ———————————-returning char

So, declare x as a function returning pointer to an array of pointer to a function returning char.

Now second one:


char (* (*x[3]) ()) [5]

1. Start from variable name ————————– x
2. Go right, find [3] ————————————–is an array of size 3
3. Go left, find * —————————–of pointers
4. Go right , find nothing but )
5. So go left, find nothing but (
6. Go right, find () ———————————— to a function
7. Go left, find * —————————————returning pointer
8. Go right, find nothing but )
9. So go left, find nothing but (
10. So go right, find [5] ————————–to an array of 5
11. Go left , find char —————————–char

So, declare x as an array of 3 pointers to a function returning pointer to an array of 5 char .

But the point is that you have to keep on going to the right: you’re not “alternating right and left”.

I think now you can go ahead with the third one and solve the rest in the world. 🙂

Check with a tool

Install cdecl:


sudo apt-get install cdecl

Run it using (on terminal):


cdecl

This will give you:


Type `help' or `?' for help
cdecl>

To find English of C gibberish, use:


explain int *x

#Press Enter, this will give you

#declare x as pointer to int

Check it on the webpage of cdecl

You can also use this to check a C declaration.

Made by Here.

You can what Linus thinks about the Spiral rule and left right rule here.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s