In C programming, complicated declarations can often be difficult to read, especially when involving pointers, arrays, and function pointers. However, by breaking them down systematically, they become easier to understand. Let’s go through some key concepts and examples.
C declarations follow the right-left rule:
() take the highest precedence.[] come next.() declarations follow.* has the lowest precedence.Let’s analyze some complex C declarations:
cCopyEditint *ptr;
ptr is a pointer (*).int).cCopyEditint **ptr;
ptr is a pointer to another pointer (*).int).cCopyEditint *arr[10];
arr is an array of 10 elements ([10]).*).int).cCopyEditint (*ptr)[10];
ptr is a pointer (*).[10]).cCopyEditint *func();
func is a function (()).*).int).cCopyEditint (*funcPtr)();
funcPtr is a pointer (*).()).int).int myFunction() {
return 42;
}
int main() {
int (*funcPtr)(); // Pointer to function
funcPtr = myFunction; // Assign function address
printf("%d", funcPtr()); // Call function via pointer
return 0;
}
int (*funcArray[5])();
funcArray is an array of 5 elements ([5]).*).()).int).cCopyEdit#include <stdio.h>
int add() { return 10; }
int subtract() { return 5; }
int main() {
int (*funcArray[2])(); // Array of function pointers
funcArray[0] = add;
funcArray[1] = subtract;
printf("%d\n", funcArray[0]()); // Output: 10
printf("%d\n", funcArray[1]()); // Output: 5
return 0;
}
int *(*funcPtr)();
funcPtr is a pointer (*).()).*).int).int value = 100;
int *getPointer() {
return &value;
}
int main() {
int *(*funcPtr)(); // Pointer to function returning int pointer
funcPtr = getPointer;
printf("%d", *funcPtr()); // Output: 100
return 0;
}
To break down a complex declaration:
() > [] > *.For example:
int (*(*fp)())[10];
fp is a pointer (*).()).*).[10]).cdecl to Simplify DeclarationsInstead of manually parsing complex declarations, you can use the cdecl tool:
Then type:
explain int (*(*fp)())[10];
Output:
declare fp as pointer to function returning pointer to array[10] of int
Alternatively, to create declarations:
cdecl> declare ptr as pointer to function returning pointer to int
Output:
int *(*ptr)();
Complicated declarations in C can be intimidating, but by following precedence rules and breaking them down systematically, they become much easier to understand. Using tools like cdecl can also simplify the process.