Search code examples
cpointersvariable-declarationfunction-declaration

Differentiating various declarations in C


While I was going through my questions, I found the these questions:

1) int*p;
2) int p(char*a)
3) int(*p(char*a))
4) int *p(void)
5) int*(*p[10])(char a)

(Please correct me if I'm wrong with my answers here.)

Q.1. is declaring a integer pointer variable 'p'

Q.2. is declaring a function p with a char pointer variable 'a' as argument.

Q.4. is declaring a void pointer(Maybe).

Can someone answer what these statements mean (and correct my answers if I'm wrong). Please answer as simple as possible. I'm quite new to programming.


Solution

  • Q.1. Correct.

    Q.2. You forgot to mention that the function, when called, returns an integer—so, that, in the program's body, one can write an integer expression like p(a) + 1—but, otherwise, correct.

    Q.4. This one is tricky. Here you have a function p() which can be called with no arguments, but which returns a pointer to integer; or, if you prefer to say it another way, which returns the address of an integer. In the program's body, one might use it for example as *p() + 1.

    You're doing fine. The usual way to read such declarations is

    • rightward away from the identifier p outward, and then, once all modifiers have been exhausted to the right,
    • leftward away from the identifier p outward.

    Like this: 8765p1234.

    The exception is if parentheses around the identifier intervene, in which case: 87(43p12)56.

    The last gets tricky, because there exist some expressions in which the identifier itself is omitted, so you have to read it like 87(4312)56.