-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path220124_c_declaration.c
More file actions
60 lines (46 loc) · 1.66 KB
/
220124_c_declaration.c
File metadata and controls
60 lines (46 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// C declaration
// tested with gcc 11.2
#include <stdio.h>
///////////////////////////////////////////////////////
// 1.
// function cannot return a function,
// but instead, it can return a pointer to a function
// compile error
//int (f_error())(); // function returning a function
int i = 42;
int *f1(int param) { i += param; return &i; };
int*(*f2())(int) { return f1; } // function returning a pointer to a function
///////////////////////////////////////////////////////
// 2.
// function cannot return an array
// but instead, it can return a pointer to an array
// compile error
//int (fa_error())[]; // function returning an array
int a[2] = {42, 239};
int (*fa())[] { return &a; } // function returning a pointer to an array
///////////////////////////////////////////////////////
// 3.
// array cannot contain functions
// but instead, array can contain pointers to function
// compile error
//int (af_error[])(); // array of function
int af1(int param) { return 42 - param; }
int af2(int param) { return 42 + param; }
int (*af[])(int) = { af1, af2 }; // array of pointers to function
// test! check that declaration shape and call shape is the same
int main()
{
printf("%i\n", * f2 ()(239));
printf("%i\n", *(*f2)()(239));
// int*(*f2())(int)
// ^
// we can omit this
printf("a[0] is %i\n", (*fa())[0]);
printf("a[1] is %i\n", (*fa())[1]);
// int (*fa())[ ]
printf("af1(239) is %i\n", af[0] (239));
printf("af2(239) is %i\n", (*af[1])(239));
// int (*af[ ])(int)
// ^
// we can omit this
}