S
S
Slavka2016-03-23 07:33:54
C++ / C#
Slavka, 2016-03-23 07:33:54

Pure C and variable number of arguments?

In general, I want to solve such a problem for myself in pure C, in order to initialize any structures with one function, here is my plan to write a function that would take void * as the first argument and then there was a list of arguments and I just added them to the pointer by offset, but I don’t know how implement it. The goal of my task is to master macros, I started that __va_args__ receives a variable number of arguments passed to the macro, but how to pull out the elements one by one?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Dubrovin, 2016-03-23
@z3apa3a

Working with arguments usually goes through va_start / va_arg / va_end. But you still need to somehow pass in the types of the structures, as printf() does, for example, or store their descriptions in some format and pass them in.

A
abcd0x00, 2016-03-24
@abcd0x00

The goal of my task is to master macros

And what about macros? You may not know, but getc() and getchar() are also often implemented as macros. You don't need to know to use them. It's the same here.
All functions with a variable number of arguments are based on the same principle: there is a mandatory argument that carries information about optional ones. It can be a string, but it can also be a number, or it can even be a structure. When entering the function, information about optional arguments (their number and type of each) is extracted from it. And then this information is used to get the arguments themselves.
First, a pointer is placed to the last mandatory argument, and then transitions are made from this position through the arguments in accordance with the sizes of their types.
To avoid manually calculating addresses and sizes each time, convenient macros are made - va_start(), va_arg(), va_end().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question