Saturday, September 3, 2011

C Program to illustrate the use of ELLIPSIS operator (...)

What is Ellipsis  ?

  Suppose we declare some prototypes:
     a) int factorial(int);
     b) int sum(int,int);

  Then the function calls should be somewhat like this :
    A)  factorial(n);
    B)  sum(a,b);

  But if we write in the following way :

  Then we will definitely encounter an error.
  That's because we have already declared the number of

arguments which the  respective functions can take. So ,

we cannot put more arguments than the specified ones.

But if this happens in the functions in C, then what about

the functions "printf()" and "scanf()". We can take any

number of arguments according to our choice. So, what

do their prototypes look like  ???

THey look somewhat like this :
                     int printf(const int *str, ...)

Now here's where the "ELLIPSIS" comes into play. This

ellipsis assures the entry of any number of argument

inputs or output as desired by the user.


After this, another question arises , how can we access

the arguments in the function.  ??

This can be done by the power of pointers. Let’s take a

pointer which points to the last argument before …
and depending on the next arguments of what we expect,

we increment the pointer and increment it accordingly.



int print(const char *str,...)

/*str has the number of integers passed*/


          int i;

          int num_count=atoi(str);

          int *num=(int *)&str;



 printf("%d ",*(num+i));}

int print_num(int num_count,...)

/*num_count contains the number of integers passed*/


          int i;

          int *num=&num_count;



 printf("%d ",*(num+i));


int main()




No comments:

Post a Comment