ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Home » C programs

va_start() and va_end() functions of stdarg.h in C

In this article, we are going to learn about the va_start() and va_end() functions of stdarg.h header file in C programming language and use it to initializes the variable argument list referred to by ap.
Submitted by Abhishek Sharma, on April 20, 2018

These are helpful function which tells us about the arguments which are being passed to the function. There are lots of cases where you don’t want to make different functions for the different numbers of argument.

For example, you have to make two functions for these things (if you are not using an array).

    add(int a, int b) {
        return a + b; 
    }

    add(int a, int b, int c) {
        return a + b +c;
    }

Now you can make a single function like this:

    add(int I, ...) {
	    va_list L;
	    int z=0;
	    va_start(L, a);
	    for (int i=0; i < a; i++)
	    z = z + va_arg(L, int);
	    va_end(L);
    }

Well, simple way is to use array.

ADVERTISEMENT

stdarg.h- va_start() and va_end() functions Example in C



#include <stdio.h>
#include <stdarg.h>

int fun(int a, ...)
{
    // define type of variable
    va_list L;
    int z;

    z = 0;

    va_start(L, a);

    // Loop to adding the int values
    for (int i=0; i < a; i++)
    {
        z = z + va_arg(L, int);
    }

    va_end(L);

    return z;
}

int main()
{
    // Define temporary variables
    int x, y, z;
    int k;

    x = 2;
    y = 3;
    z = 4;

    // calling function
    k = fun(3, x, y, z);

    // displaying message with result
    printf("Total of %d, %d and %d is %d\n", x, y, z, k);

    return 0;
}

Output

va_start() and va_end() functions of stdarg.h in C

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.