Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function returns different numbers when called in another function

\
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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading