Function in struct

Source: Internet
Author: User

The C language is really flexible. Today, I found the application of functions in the structure, and I checked some information to summarize it.

In fact, the struct is similar to the class functions in C ++, but it is process oriented and has no scope requirements, such as public.

You can define a function in the struct, and then call it like a class call method. You can also define a function pointer and assign a value to it during the call (the pointer you want to call ), in this case, C can also get a temporary string of object-oriented information. Haha. You can try it.

1 # include <stdio. h>
2 struct Square
3 {
4 int length;
5 Int width;
6 int height;
7 int (* Add) (int A, int B );
8 };
9 int square_add (int A, int B)
10 {
11 return A + B;
12}
13 int bulk (INT length, int width, int height)
14 {
15 struct square squ =
16 {
17. Length = length,
18. width = width,
19. Height = height,
20 Add: square_add,
21 };
22
23 printf ("add () is % d/N", sqlu. Add (100,200 ));
24 printf ("length is % d/N", SQU. Length );
25 printf ("width is % d/N", SQU. width );
26 printf ("height is % d/N", SQU. Height );
27 return squ. length * squ. Width * squ. height;
28}
29 int main ()
30 {
31 printf ("the square is % d/N", bulk (100,200,300 ));
32 return 0;
33}
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.