Ellipsis is there consecutive period (.) with no
white space. With the help of ellipsis we can write a function of variable
number of parameter. For example:
#include<stdio.h>
int number(int a,...){
return a;
}
int number(int a,...){
return a;
}
int main() {
int i;
i=number(5,4,3,2,1);
printf("%d",i);
return 0;
}
Output: 5
}
Output: 5
Ellipsis can be
used as a variable number of parameters or a variable which stores
variable number of arguments. For example:
#include<stdio.h>
int dynamic(int,...);
int main(){
int x,y;
x=dynamic(2,4,6,8,10,12,14);
y=dynamic(3,6,9,12);
printf("%d %d ",x,y);
return 0;
}
int dynamic(int s,...){
void *ptr;
ptr=...;
(int *)ptr+=2;
s=*(int *)ptr;
return s;
}
Here dynamic
function is example of variable number of arguments while pointer ptr is
example of variable which is storing variable number of arguments.
In header file stdarg.h has three macro va_arg, va_end, va_start, with help of this macro we can know other parameter of a function in case of variable number of parameters. Syntax:
void va_start (va_list ap,lastfix)
type va_arg(va_list ap,type)
void va_end(va_list ap);
va_list is list
of data .
lastfix is a
last fixed parameter used in a function of variable number of parameters.
type is used to
know which data type are using in function of variable number of parameters .
va_arg always
returns next parameter from right to left.
va_start set the
pointer ap to the first parameter from right side of a function of variable
number of parameters.
va_end help in
the normal return. Example:
#include <stdio.h>
#include <stdarg.h>
void sum(char *msg, ...) {
int total = 0;
va_list p;
int arg;
va_start(p, msg);
while ((arg =
va_arg(p,int)) != 0) {
total += arg;
}
printf(msg,
total);
va_end(p);
}
int main() {
sum("The
total sum is %d\n", 5,7,11,8);
return 0;
}
Output: 31
Properties of
variable number of arguments:
1. First
parameter must be any other data type in case of variable
number of arguments.
Invalid declaration
of function:
int (...);
Valid declaration
of function:
int (char c,...);
void(int,float,...);
2.
We cannot pass
any other data type after the variable number of arguments.
Invalid
declaration of function:
int (int a,...,int b);
3. We cannot
give any blank space between any two periods (dot) in the ellipsis.
Invalid
declaration:
int (float b,. . .);
4. In place of
ellipsis we can pass the data either of same type or different type.
#include <stdio.h>
#include <stdarg.h>
int flue(char c,...);
int main(){
int x,y;
x=flue('A',1,2,3);
y=flue('1',1.0,1,'1',1.0f,1l);
printf("%d %d",x,y);
return 0;
}
int flue(char c,...){
return c;
}
Output: 65 49
No comments:
Post a Comment