C tip: Convert struct parameters to indefinite Parameters

Source: Internet
Author: User

Cool Shell

The following section of the program is a small C language skill. It shows how to convert a function with a struct parameter into a Variable Parameter Function, the macro and built-in macro "_ VA_ARGS _" are used. The following program can be compiled normally under GCC:

1234567891011121314151617181920 # include <stdio. h> # define func (...) myfunc (struct mystru) {__ VA_ARGS __}) struct mystru {const char * name; int number ;}; void myfunc (struct mystru MS) {printf ("% s: % d ", ms. name? : "Untitled", ms. number);} int main (int argc, char ** argv) {func ("three", 3); func ("hello"); func (. name = "zero"); func (. number = argc ,. name = "argc",); func (. number = 42); return 0 ;}

From the above section of the program, we can see that a function called myfunc is changed by the macro of func. What myfunc needs is a structure called mystru. However, through the macro, the parameter struct mystru is changed to a function in the Variable Parameter List. The above program is output,


Three: 3
Hello: 0
Zero: 0
Argc: 1
Untitled: 42

Although this is not a good practice, you can learn about the strange usage of C in this world from another aspect. If you expand the macro, you will understand why. The following is the macro scale:

12345 myfunc (struct mystru) {"three", 3}); myfunc (struct mystru) {"hello"}); myfunc (struct mystru ){. name = "zero"}); myfunc (struct mystru ){. number = argc ,. name = "argc",}); myfunc (struct mystru ){. number = 42 });

Related Article

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.