As a beginner of C, if you write a function that asks for the perimeter of a quadrilateral, I tend to write as follows:
Calculate the perimeter of a quadrilateral
#include <stdio.h>
#define RECTANGLE 0//Rectangle
#define SQUARE 1//square
Polygon
struct polygon{
int type;
int length;
int width;
};
int get_circumference (struct polygon pygn)
{
if (Pygn.type = = RECTANGLE)
{
Return 2 * (Pygn.length + pygn.width);
}
else if (Pygn.type = SQUARE)
{
Return 4 * pygn.width;
}
Else
{
Todo
}
}
int main (void)
{
struct polygon Pygn_rec, pygn_squ;
Pygn_rec.type = RECTANGLE;
Pygn_rec.width = 6;
Pygn_rec.length = 10;
Pygn_squ.type = SQUARE;
Pygn_squ.width = 6;
printf ("Get Cir Rec is:%d\n", Get_circumference (Pygn_rec));
printf ("Get Cir Squ are:%d\n", Get_circumference (Pygn_squ));
return 0;
}
Today, after reading the <linux C programming one-stop learning > "function type and function pointer" (http://learn.akae.cn/media/ch23s08.html), I learned a better way:
Calculate the perimeter of a quadrilateral
#include <stdio.h>
#define RECTANGLE 0//Rectangle
#define SQUARE 1//square
Polygon
struct polygon{
int type;
int length;
int width;
};
int Get_rectangle_cir (struct polygon pygn)
{
Return 2 * (Pygn.length + pygn.width);
}
int Get_square_cir (struct polygon pygn)
{
Return 4 * pygn.width;
}
Int (* get_circumference[]) (struct polygon pygn) = {get_rectangle_cir, get_square_cir};
#define GET_CIR (PYGN) Get_circumference[pygn.type] (PYGN)
int main (void)
{
struct polygon Pygn_rec, pygn_squ;
Pygn_rec.type = RECTANGLE;
Pygn_rec.width = 6;
Pygn_rec.length = 10;
Pygn_squ.type = SQUARE;
Pygn_squ.width = 6;
printf ("Get Cir Rec is:%d\n", Get_cir (Pygn_rec));
printf ("Get Cir Squ are:%d\n", Get_cir (Pygn_squ));
return 0;
}
when calling Get_cir (PYGN), index with the Type field Pygn.type from the pointer array get_ Circumference to invoke the corresponding function pointer, the
can also reach if ... else ... effect, but this is better than this, with each function doing just one thing,
without having to use the If ... else ... Take into account several things, such as Get_rectangle_cir and Get_square_cir each, and
are independent of each other, without coupling their code to a function.
"Low-coupling, cohesion well-structured classes-coupling, high cohesion" is a fundamental principle of programming,
which enables better reuse of existing code, making it easier to maintain code. If the Type field Pygn.type another value, the
only needs to add a new set of functions, modify the function pointer array, and the original function can still be reused without modification.