va_start as array - c++

According to what I read about the va_arg macro, it that retrieves the next argument pointed by the argument list. Is there any way to choose the index of the argument I want to get, like an array index?
For example I need to do an operation where I need to call at least 3 times the va_arg macro but I want those 3 times to retrieve the same argument and not the next one on the list. One solution could be using a function and passing the argument, but I don't want that.
Also if there is no other macros able to do this, how can I reference to the start of the array arguments by a pointer? I know its not portable and not type safe, etc, etc. Just for the sake of learning.
Here is an example code of how i want to implement it:
bool SQLBase::BindQuery (char* query, int NumArgs, ...)
{
va_list argList;
va_start(argList, NumArgs);
SQLPrepare (hstmt, query, SQL_NTS);
for (int x = 0; x < NumArgs; x++)
{
SQLBindParameter (hstmt, (x+1), GetTypeParameter (va_arg(argList, SQLPOINTER*), SQL_C_CHAR, SQL_CHAR, 10, 0, va_arg(argList, SQLPOINTER*), va_arg(argList, SQLLEN), &recvsize[x]);
}
The va_arg is called 3 times for the SQLBindParameter function and i want the first 2 times to point to the same argument, not increasing the count member on the argument list.

First of all, calling va_arg multiple times in your function invocation is hairy, since you don't know in which order these calls happen. You need to do this beforehand, so your arguments are retrieved in the correct order.
Second, no: there is no array-style usage auf va_list. This is because va_list doesn't know a thing about the arguments on the stack; you are supplying the type in your va_arg calls, and va_arg can then increase the (internal/conceptual) pointer contained in the va_list because it knows the size of that argument. Getting to the third argument would require you to supply the types of the first two.
If all the arguments are the same size (like "void*") you can always just make a loop that calls va_arg the appropiate number of times. This is "kind of" portable if you can be reasonably sure that your arguments are in fact the same size. I'm not too confident that doing this would be the best course of action, though -- the need to do it might indicate that a different setup would be more appropiate, like passing an array in the first place instead of using a variable argument function.
You can also just take the address of a function argument and assume they are on the stack in some order. This is horribly unportable since you need to know about calling conventions which can vary between compilers, and may even change based on compilation options. I would definitely advise to NOT do something like this.

Related

How to construct an XlaOp?

There are a number of functions for creating XlaOps from native C++ values. I'm trying to figure out how to use each to construct a graph. I've gone through xla_builder.h and picked out some candidates, omitting overloads and convenience wrappers. The two most likely candidates seem to be
// Enqueues a "retrieve parameter value" instruction for a parameter that was
// passed to the computation.
XlaOp Parameter(XlaBuilder* builder, int64 parameter_number, const Shape& shape,
const string& name);
// Enqueues a constant with the value of the given literal onto the
// computation.
XlaOp ConstantLiteral(XlaBuilder* builder, const LiteralSlice& literal);
Am I right in thinking Parameter is for "symbols", while ConstantLiteral is for constant values? For example, in f(x) = x + 1, we'd encode 1 as a ConstantLiteral, and then for x we could either
write f(x) as a C++ function, and at application site use another ConstantLiteral for our value of x, or
encode x using Parameter and build an XlaComputation from the corresponding XlaBuilder. That said, I'm not clear on how to actually call the XlaComputation with a Literal, other than with LocalClient which doesn't work with to multiple XlaComputations afaict.
What's the difference between these two approaches? Is one better than the other? I notice the former doesn't appear possible for higher-order functions: those which accept XlaComputations.
Next there's
Infeed, which I'd guess is a streaming version of Parameter.
Recv which looks like a way to pass data between computations, but doesn't actually create a completely new XlaOp itself.
ReplicaId, Iota, and XlaOp CreateToken(XlaBuilder* builder); appear largely irrelevant for this discussion.
Have I got this right? Are there any other important functions I've missed?

Use one pointer for sprintf variadic argument

I am writing a function, that takes a variadic argument list and produces a formated string from those. The problem is, that i use sprintf to create the string and i need to explicity list all paramaters, while programming
sprintf(string, format, a0, a1, a2, ...);
On cppreference however the description of sprintf says, that ...
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace
a format specifier in the format string (or a pointer to a storage
location, for n).
What i understand like, that i can store all the data to a pointer location and hand the pointer to sprintf.
int arr[X];
arr[0] = a0;
...
sprintf(string, format, &arr);
Trying that resulted in an unexpected behavior. Only numbers were written to the string.
Does it actually work that way and is there maybe a better solution?
My first attempt was to add each variadic argument separatly to the string, but that produced a lot of calls to sprintf, what i want to avoid.
Is it possible to pass the variadic argument list from one function to another?
Okay ... why did i not find this sooner...
The solution for me was to use vsnprintf instead of sprintf. That way one can pass the va_list to a formated string function and it is secure.
How to pass variable number of arguments to printf/sprintf

Can we make a scanf like function that returns true when all parameters are populated and false otherwise without looping through all variables?

I would like to do this in C++ (or C if required). I looking into Variadic Functions and the only method I could come up with seemed rather poor in terms of performance:
scanner(const char * string, const char * format, ...) // ... is the variables
{
bool got_them_all(false);
size_t length_of_list(0);
va_list variables_list;
va_start(variables_list, format);
// Loop through variables_list and count until we run out of items
...
if (length_of_list == sscanf(string, format, va_list))
{
got_them_all = true;
}
va_end(variables_list);
return got_them_all;
}
In my specific use case these are command parameters coming in and I know the string format. What I am trying to do is avoid errors where I count 5 parameters but pass scanf (OK really sscanf in my case) 4 or 5. I would call the function with:
allOK = scanner(command_cstring, "CMD:%02d,%02d", inta, intb);
Now in that case I can easily see that there are 2 parameters so I could do the if (2 = scanner(command_cstring, "CMD:%02d,%02d", inta, intb)); reliably. When it is more than half a dozen parameters I think my odds of not getting something wrong get rather high.
I would rather not add a loop to count parameters to my dynamic incoming string processing. It sounds like a waste of CPU time on this small embedded system.
There seems no standard way to do sizeof(va_list).
Variadic Templates sound hopeful. I don't mind the compile time computing load as at that point the code has the longest list of variables I am going to enter. I do not have a C++11 compiler available for me, but I would be happy to accept a solution that needed one for the future. If I had a C++11 option today then I would probably be trying to get something together myself right now.
There is no way to tell at runtime how many arguments are passed to a varargs function. Nor can you tell what the types of the arguments are. In short, it is your responsibility to get it right.
However, if you are using gcc or clang and your format strings are literal strings, then the compiler will warn you if there is a mismatch between the format string and the number or types of the arguments. This warning is enabled with -Wformat, but it is also one of the many useful warnings enabled with -Wall. (If you are compiling without -Wall, you are effectively wearing a blindfold.)
template<class...Ts>
bool scanner(const char * string, const char * format, Ts const&...ts)
{
size_t num_scanned = sscanf(string, format, ts...);
bool got_them_all = num_scanned == sizeof...(ts);
return got_them_all;
}
would do it. Note, however, that if you specify more parameters in the string than you pass, you'll do undefined behavior within sscanf.
Annoying, you'll want to scan format for the format specifiers yourself prior to calling sscanf to make it safe. At least do this in a debug build.

Different inputs for the same function

So I have a function that takes in 2 different inputs.
I've ran into the situation, however, where I very occasionally need a third input. Most of the time I don't though.
The solution I currently have is that the actual function I want to use is only called by 2 other functions. These two functions have the same name, but 1 takes 3 input and the other 2 (with this one just setting a null value to the third input before calling the original function).
This works quite well, but it feels like there might be a much better way of handling this type of problem. The only other solution I have is to declare a null value of the third input every time I go to call the first function, but that seems even messier.
Is there a better way to do this? Is it bad form the way I've written it?
Default arguments:
void foo (int x, int y, int z = 0);
Unless you pass a third value, z will be 0 by default inside the function.

c++ best way to call function with const char* parameter type

what is the best way to call a function with the following declaration
string Extract(const char* pattern,const char* input);
i use
string str=Extract("something","input text");
is there a problem with this usage
should i use the following
char pattern[]="something";
char input[]="input";
//or use pointers with new operator and copy then free?
the both works but i like the first one but i want to know the best practice.
A literal string (e.g. "something") works just fine as a const char* argument to a function call.
The first method, i.e. passing them literally in, is usually preferable.
There are occasions though where you don't want your strings hard-coded into the text. In some ways you can say that, a bit like magic numbers, they are magic words / phrases. So you prefer to use constant identifier to store the values and pass those in instead.
This would happen often when:
1. a word has a special meaning, and is passed in many times in the code to have that meaning.
or
2. the word may be cryptic in some way and a constant identifier may be more descriptive
Unless you plain to have duplicates of the same strings, or alter those strings, I'm a fan of the first way (passing the literals directly), it means less dotting about code to find what the parameters actually are, it also means less work in passing parameters.
Seeing as this is tagged for C++, passing the literals directly allows you to easily switch the function parameters to std::string with little effort.