\ I've created a practice project for my test and I can't seem to get around this problem. I need a function that grabs the input and when called in another function, the input will be used to solve a problem. \ here is my code
#include <stdio.h>
int get()
{
int one,two,three,four;
scanf("%d %d %d %d", &one, &two, &three, &four);
return one,two,three,four;
}
int add()
{
int one,two,three,four;
int result1, result2, result3;
get();
result1 = one + two;
if (result1 == three)
{
result2 = four - three;
result3 = result2 + four;
printf("Added %d, 5th number is %d", result2, result3);
}
else
{
printf("error, %d %d %d %d", one, two, three, four);
}
}
int main()
{
add();
return 0;
}
When I put the scanf statement inside the function, it works. But when I use the function to get the input, I get different numbers
In the return statement of the function get
return one,two,three,four;
there is an expression with the comma operator. Its value is the value of the last operand. That is the function returns the value of the variable four
.
And moreover the returned value is not used in the caller. So you are dealing with uninitialized variables within the function add
.
If you need to return four values then return them trough parameters by reference. For example
void get( int *one, int *two, int *three, int *four;)
{
scanf("%d %d %d %d", one, two, three, four);
}
and call the function like
get( &one, &two, &three, &four );
Or the function can return an integer that will signal whether the input was successful as for example
int get( int *one, int *two, int *three, int *four;)
{
return scanf("%d %d %d %d", one, two, three, four) == 4;
}
You can check the return value in the function add
before performing calculations.
Pay attention to that the function add
returns nothing. So declared its return type as void
.
void add( void );