I am trying to convert some Java code into C. The Java code goes like this:
public static int minimum( int... minimum ) {
assert( minimum.length > 0 );
if ( minimum.length > 0 )
.... // some code that i am able to translate to C without any hassle
}
Now I understand how to have varargs in C by using the stdarg.h header and using the macros provided. However I am stuck doing the minimum.length part.
I have tried strlen but the terminal is giving me an incompatible integer to pointer conversion warning. Is there any way in C where I can replicate the same thing that Java does?
Not directly, as pointed out by #MichaelBurr, you need to pass the number of elements or use a sentinel.
An indirect way to do this is using compound literals:
#include <stdio.h>
#include <stdarg.h>
#include <limits.h>
#define minimum(...) fnminimum(sizeof((int []) {__VA_ARGS__}) / sizeof(int), __VA_ARGS__)
static int fnminimum(int n, ...)
{
int num, min = INT_MAX;
va_list ap;
va_start(ap, n);
while (n--) {
num = va_arg(ap, int);
if (num < min) {
min = num;
}
}
va_end(ap);
return min;
}
int main(void)
{
int a = 1;
printf("%d\n", minimum(2, 30, 7, a++, 4));
return 0;
}
Another (ugly) method using NARGS macros (limited to N args):
#include <stdio.h>
#include <stdarg.h>
#include <limits.h>
#define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,_9,N,...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1)
#define minimum(...) fnminimum(NARGS(__VA_ARGS__), __VA_ARGS__)
static int fnminimum(int n, ...)
{
int num, min = INT_MAX;
va_list ap;
va_start(ap, n);
while (n--) {
num = va_arg(ap, int);
if (num < min) {
min = num;
}
}
va_end(ap);
return min;
}
int main(void)
{
printf("%d\n", minimum(2, 30, 7, 1, 4));
return 0;
}
Output:
1
There is no built-in way to get the number of vararg arguments passed in C.
You need to do one of the following:
pass in a count explicitly,
pass in a count implicitly (as printf() does via the number of conversion specifiers)
or use a sentinel value (such as NULL or 0) to indicate the end of the vararg list
I have seen schemes that use macros and the __VA_ARGS__ identifier to automatically place a sentinel at the end of the varargs list when calling a function.
Related
Whenever we use variable argument function in C language, we have to provide the total number of arguments as the first parameter. Is there any way in which we can make a function with variable arguments without giving the total number of arguments?
[update from comment:]
I want to use functions like sum(1,2,3) should return 6. i.e, no counter should be there.
Several ways:
pass simple, explicit count (which you don't want in this question)
pass some format string, similar to printf and scanf
pass some "mode" parameter, and have each mode require specific varargs
have all varargs to be of same type, and require last argument to be some special value, AKA sentinel value, such as NULL for pointer list or max/min value of the type for integer types, or NaN for doubles.
However you do it, you have to have some way for the function to know the types of the varargs, as well as a way for it to know when they end. There is no built-in way in C, argument count is not passed to the function.
I want to use functions like sum(1,2,3) should return 6. i.e, no counter should be there
You could define a sentinel. In this case 0 might make sense.
/* Sums up as many int as required.
Stops adding when seeing the 1st 0. */
int sum(int i, ...)
{
int s = i;
if (s)
{
va_list ap;
va_start(ap, i);
/* Pull the next int from the parameter list and if it is
equal 0 leave the while-loop: */
while ((i = va_arg(ap, int)))
{
s += i;
}
va_end(ap);
}
return s;
}
Call it like this:
int sum(int i, ...);
int main(void)
{
int s = sum(0); /* Gives 0. */
s = sum(1, 2, 3, 0); /* Gives 6. */
s = sum(-2, -1, 1, 2, 0); /* Gives 0. */
s = sum(1, 2, 3, 0, 4, 5, 6); /* Gives 6. */
s = sum(42); /* Gives undefined behaviour! */
}
The sum() function alternatively could also look like this (but would do one useless addition of 0):
/* Sums up as many int as required.
Stops adding when seeing the 1st 0. */
int sum(int i, ...)
{
int s = i;
if (s)
{
va_list ap;
va_start(ap, i);
/* Pull the next int from the parameter list and if it is
equal 0 leave the do-loop: */
do
{
i = va_arg(ap, int);
s += i;
} while (i);
va_end(ap);
}
return s;
}
You don't have to supply that number of arguments. For instance, consider the signature for printf:
int printf( const char* format, ... );
It "finds out" how many arguments it needs by parsing the string you give it. Of course, your function needs to know the amount of arguments in some way, otherwise what sense does it make for it to take a variable number of arguments?
It is possible to create a variadic function which takes a count as the first argument, then use variadic macros to add the count value automatically:
#include <stdarg.h>
#define count_inner(a1, a2, a3, a4, a5, num, ...) (num)
#define count(...) count_inner(__VA_ARGS__, 5, 4, 3, 2, 1)
#define sum(...) sum_func(count(__VA_ARGS__), __VA_ARGS__)
int sum_func(int count, ...)
{
va_list ap;
va_start(ap, count);
int total = 0;
while(count--)
total += va_arg(ap, int);
va_end(ap);
return total;
}
Using the sum macro instead of sum_func allows the count to be omitted, provided there are between 1 and 5 arguments. More arguments/numbers can be added to the count_inner/count macros as required.
int main(void)
{
printf("%d\n", sum(1));
printf("%d\n", sum(1, 2));
printf("%d\n", sum(1, 2, 3));
printf("%d\n", sum(1, 2, 3, 4));
}
Output:
1
3
6
10
Well, the problem is that you have to somewhat indicate to the function that your argument list is exhausted. You've got a method from printf(3) which is that you can express the order and the type of arguments in your first parameter (forced to be a string arg) you can express it in the first parameter, or, for the adding, as the value 0 doesn't actually add to the sum, you can use that value (or some other at your criteria) to signal the last parameter. For example:
int sum(int a0, ...)
{
int retval = a0;
va_list p;
va_start(p, a0);
int nxt;
while ((nxt = va_arg(p, int)) != 0) {
retval += nxt;
}
return retval;
}
This way, you don't have to put the number of arguments as the first parameter, you can simply:
total = sum(1,2,3,4,5,6,7,8,9,10,0);
But in this case you have to be careful, that you never have a middle parameter equal to zero. Or also you can use references, you add while your reference is not NULL, as in:
int sum(int *a0, ...)
{
int retval = *a0;
va_list p;
va_start(p, a0);
int *nxt;
while ((nxt = va_arg(p, int*)) != NULL) {
retval += *nxt;
}
return retval;
}
and you can have:
int a, b, c, d, e, f;
...
int total = sum(&a, &b, &c, &d, &e, &f, NULL);
The following max function is supposed to return 5 but it returns 4294967294 instead. I suspect the weird behavior arise from casting variables but couldn't figure it out. Can someone detect the fault?
System: Windows 7 (64 bits), mingw64
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <stdarg.h>
#include <inttypes.h>
int64_t max(int64_t n, ...) {
va_list v;
int64_t i, t, max = INT64_MIN;
va_start(v, n);
for (i = 0; i < n; i++) {
t = va_arg(v, int64_t);
if (max < t) {
max = t;
}
}
va_end(v);
return (max);
}
int main(int argc, char **argv) {
printf("max(3, 1, 5, -2) : %3I64d\n", max(3, 1, 5, -2));
return (0);
}
The compiler doesn't know that 1,5 and -2 are supposed to be type int64_t. So it will treat them as normal ints and will only use that much space on the stack for them.
You then read them as int64_t which is certainly larger than int and so your input and your var_args are out of alignment.
One way to fix, cast to int64_t at the call site.
printf("max(3, 1, 5, -2) : %"PRId64"\n", max(3, (int64_t)1, (int64_t)5, (int64_t)-2));
You could also obviously explicitly pass int64_t typed variables.
I'm reading about how to pass optional arguments to function. But I'm unable to understand those. When I see examples, they are confusing and a bit complex. So I just started with a very simple program with what I have understood up to now.
The below program just prints the variables.
void print(int x, ...)
{
va_list ap;
int i = 4; // I know I'm passing only 4 opt variables.
int num;
va_start(ap, x);
while(i--) { // How to know how many variables came in real time?
num = va_arg(ap, int);
printf("%d\n", num);
}
va_end(ap);
return;
}
int main()
{
print(1,2,3,4,5);
return 0;
}
I don't know above program is right or not. But it's working. When I change the i value to 5 printing garbage. How to know how many arguments I got (like argc in main)?
There is no way of knowing how many arguments are passed from inside a variable-argument function, that's why functions such as printf are using special format strings that tells the function how many arguments to expect.
Another way is of course to pass the number of "extra" arguments as the first argument, like
print(4, 1, 2, 3, 4);
Or to have a special value that can't be in the list as last argument, like
print(1, 2, 3, 4, -1);
You also have to take note that the last non-va argument you pass to the function (the argument named num in your case) is not included in the va_list, so in your case with the shown code with 4 as hardcoded number of arguments you will still print garbage, as you pass 1 for the num argument and then three va_list arguments.
Also take care because you use num as both argument and a local variable name.
You can take a look to NARGS macro
Adapted to your code:
#include <stdio.h>
#include <stdarg.h>
#define NARGS_SEQ(_1,_2,_3,_4,_5,_6,_7,_8,_9,N,...) N
#define NARGS(...) NARGS_SEQ(__VA_ARGS__, 9, 8, 7, 6, 5, 4, 3, 2, 1)
#define print(...) fnprint(NARGS(__VA_ARGS__), __VA_ARGS__)
void fnprint(int n, ...)
{
va_list ap;
int num;
va_start(ap, n);
while (n--) {
num = va_arg(ap, int);
printf("%d\n", num);
}
va_end(ap);
return;
}
int main(void)
{
print(1, 2, 3, 4, 5);
return 0;
}
EDIT:
If you want to use the same name for macro and function, use () to stop the preprocessor from expanding the function definition:
#define print(...) print(NARGS(__VA_ARGS__), __VA_ARGS__)
void (print)(int n, ...) /* Note () around the function name */
{
...
EDIT 2: Another (ugly) method (but without restriction in the number of args) using compound literals (std 99) and sizeof:
#include <stdio.h>
#include <stdarg.h>
#define print(...) print(sizeof((int []) {__VA_ARGS__}) / sizeof(int), __VA_ARGS__)
void (print)(int n, ...)
{
va_list ap;
int num;
va_start(ap, n);
while (n--) {
num = va_arg(ap, int);
printf("%d\n", num);
}
va_end(ap);
return;
}
int main(void)
{
print(1, 2, 3, 4, 5);
return 0;
}
print is expanded to:
print(sizeof((int []) {1, 2, 3, 4, 5}) / sizeof(int), 1, 2, 3, 4, 5);
But constructions like print(1, 2, 3, a_var++, 4, 5); or print(1, 2, some_func_returning_int(), 4, 5); evaluates a_var++ and some_func_returning_int() two times, thats a big problem.
Another ugly way for both int and strings:
#include <stdio.h>
#include <stdarg.h>
#define print(...) fnprint("{" # __VA_ARGS__ )
fnprint(char *b) {
int count = 0, i;
if (b[1] != '\0') {
for (i =2; b[i]; i++) {
if (b[i] == ',')
count++;
}
count++;
}
printf("\ncount is %i\n", count);
}
int main(void)
{
print();
print("1", "2");
print(1, 2, 3, 4, 5);
return 0;
}
Can we pass variable number of arguments to a function in c?
Here is an example:
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
int maxof(int, ...) ;
void f(void);
int main(void){
f();
exit(EXIT SUCCESS);
}
int maxof(int n_args, ...){
register int i;
int max, a;
va_list ap;
va_start(ap, n_args);
max = va_arg(ap, int);
for(i = 2; i <= n_args; i++) {
if((a = va_arg(ap, int)) > max)
max = a;
}
va_end(ap);
return max;
}
void f(void) {
int i = 5;
int j[256];
j[42] = 24;
printf("%d\n", maxof(3, i, j[42], 0));
}
If it is a function that accepts a variable number of arguments, yes.
Yes, if the function accepts variable arguments. If you need to make your own variable-argument function, there are macros that begin with va_ which give you access to the arguments.
make sure that the variable argument list should always be at the end of the argument list
example: void func(float a, int b, ...) is correct
but void func(float a, ..., int b) is not valid
"You should consider that using variadic functions (C-style) is a dangerous flaw," says Stephane Rolland. You can find his helpful post here.
How can I pass any number of arguments in User define function in C?what is the prototype of that function?It is similar to printf which can accept any number of arguments.
Look here for an example.
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
int maxof(int, ...) ;
void f(void);
main(){
f();
exit(EXIT SUCCESS);
}
int maxof(int n args, ...){
register int i;
int max, a;
va_list ap;
va_start(ap, n args);
max = va_arg(ap, int);
for(i = 2; i <= n_args; i++) {
if((a = va_arg(ap, int)) > max)
max = a;
}
va_end(ap);
return max;
}
void f(void) {
int i = 5;
int j[256];
j[42] = 24;
printf("%d\n",maxof(3, i, j[42], 0));
}
Such a function is calle variadic, but such functions are much less useful than they might at first seem. The wikipedia page on the topic is not bad, and has C code.
The basic problem with such functions is that the number of parameters cannot in fact be variable - they are must be fixed at compile time by a known parameter. This is obvious in printf:
printf( "%s %d", "Value is", 42 );
The number of % specifiers must match the number of actual values, and this is true for all other uses of variadic functions in C, in one form or another.