Abdulaziz
Abdulaziz

Reputation: 2211

How are these two pointers different from each other?

I'm new to C language and pointers in general. So my understanding of these two things is basic.

I've been trying to create a structure that hold pointers to functions, nothing fancy. While doing so; I noticed that this statement:

int *func()
doesn't work. while this one actually works:

int (*func)()

What's the difference between them? Is it because the first statement is only a pointer to integer. while the other pointer, somehow, points to a function? How so?

Upvotes: 2

Views: 144

Answers (1)

Jimbo
Jimbo

Reputation: 4515

int *func(void)

Defines a function named func that has no parameters and returns a pointer to an integer

int(*func)(void)

Defines a pointer to a function that has no parameters and returns an integer

The reason for this difference is operator precedence. Parerenteses have a higher precendence than *. Therefore in the first expression int *func() the function-parenthesis have the highest precedence and are considered first, so associate with the symbol func so the compiler knows that func is a symbol for a function. Therefore the rest is the return.

In the second instance int(*func)() there is an extra set of parenthesis. Inside the first parenthesis we see *func. As the parenthesis is the highest precendence (left-to-right) the compiler must interpret the contents of this set... *func is a pointer. OK a pointer to what? Look right and we see () so it is a pointer to a function. Then look left to see the return type.

Hope this makes sense :) Also try How to interpret complex C/C++ declarations on CodeProject.com. It talks about something called the "Right-left rule", which is "...a simple rule that allows you to interpret any declaration...". It's a little more than half way down the page...

Also try cdecl: C gibberish ↔ English. It's quite a nice implementation of the cdecl utility.

enter image description here

Upvotes: 9

Related Questions