Showing posts with label PROGRAMMING. Show all posts
Showing posts with label PROGRAMMING. Show all posts

Thursday, 27 December 2018

How can we write a function with Variable Arguments ???

I am sure there won't be any C-programmer who never use 'printf()' function. But have you noted its specialty ??  I can take n-number of arguments. The type and number of arguments are also part of the signature of a function. Still how is it possible ?

I guess there are enough questions . Now time to answer. 

The first time when I thought about this is while I am doing an embedded program for a LCD display. I was thinking about a printf kind of function which can take any number of arguments and display.

This can be done by va (Virtual Argument)api which are defined in the header file <stdarg.h> .

va_list, va_start , va_arg and va_end are the most useful apis available from this. Let me explain these with an example.

This is my function prototype which takes any number of arguments and will print the sum.

void sum_numbers(int num,...);


How can it be implemented ?

int sum_numbers(int num,...)
{


va_list args; // Here we created a pointer that will point to the first element of the argument list.
va_start(args,num); //Here we are initializing the pointer with the first element in the list; The
                  // second argument should be the last argument of the function that comes before ellipses.
int sum=0;
fot(int i=0; i<num; i++)
{
int element=va_args(num,int);
/* Here each arguments are being retrieved. Here I have assumed that all arguments are integer type.
    But if you are not sure you can always pass a format string to know type.

sum +=element;
}

va_end(args); // Before function returns we have to close it by this api.

return sum;
}

I guess embedded engineers may meet many use cases of this api. :-)




RC Oscillator Vs Crystal Oscillator

RC Oscillators and Crystal Oscillators are so common in Embedded world. Nowadays most of the controllers are coming with inbuilt RC Oscilla...