Reputation: 894
I don't know how to fill up the sentence "if initial_value is passed". Do I have to use the variable argument? It isn't very readable to me, so I'm finding out other methods.
Help me please..
int *func (int initial_value) {
int *number;
number = malloc(sizeof(int));
if ("if initial_value is passed") *number = initial_value;
else scanf("%d", &number);
return number;
}
Upvotes: 3
Views: 3130
Reputation: 335
In C (and C++) calling a funciton without its parameters will result in a compile time error. So the function cannot be called without the parameter.
I think what you are looking for are default arguments, which is a C++ feature. It is not available in normal C.
A way to implement something similar in C is possible through pointers:
int * func (int * initial_value) {
int x;
if( initial_value == NULL ) {
x = 5;
} else {
x = *initial_value;
}
//...more code and return
}
//when you call it use:
func( NULL ); // x = 5
int arg = 7;
func( &arg ); // x = 7
Side note:
scanf("%d", &number); -> scanf("%d", number); //because number already is a pointer
Upvotes: 6