I am learning C and C++. I wrote a program in C++ and I am writing the same program in C. I want to use structs in C to mimic the classes I wrote in C++. To this end, I wrote test code that (1) creates a typedef
to a function pointer, (2) a struct with the typedef
as a member, and (3) assigns the member to a compatible function.
#include <stdio.h>
// comment 1 -- see next line
typedef int (*type_def_func_ptr) (int, int);
int result(int x, int y){
int temp_result = x + y;
return temp_result;
}
struct TEST_STRUCT {
int day;
int month;
int year;
type_def_func_ptr tdfp;
};
int main(){
struct TEST_STRUCT MyStruct;
MyStruct.day = 28;
MyStruct.month = 9;
MyStruct.year = 2024;
// comment 2 -- see next line
MyStruct.tdfp = result;
int result1 = MyStruct.tdfp(28, 9);
printf("Result1 is %d\n", result1);
}
The code works. I don't understand, however, why the code works as written without (1) result()
being *result()
(comment 1) or (2) without MyStruct.tdfp = result being = &result
(comment 2). The code still works with (2) being &result
or *result
, which leads me to believe that the compiler is interpreting what I wrote instead of blindly compiling what I wrote.
int result1 = MyStruct.tdfp(28, 9);
and int result1 = (*MyStruct.tdfp)(28, 9);
do the same thing.
MyStruct.tdfp = result;
and MyStruct.tdfp = &result;
also do the same thing.
These convenience "shortcuts" do the same thing as in C++ (in which you only need &
to take the address of functions if they are member functions).