Search code examples
cif-statementreturnreturn-value

Operations with return values in C


I'm new to C and trying to write a super basic program that compares 3 numbers and returns the biggest.

But when I try to print some text with if functions, it skips 2 if and goes to else. I might told it more complicated than it is. :)

OK, here is my code:

#include <stdio.h>

int a;
int b;
int c;

int max(int a, int b, int c) {
    
    if (a>b && a>c) {
        return a;
    }
    
    else if (b>a && b>c) {
        return b;
    }
    
    else {
        return c;
    }
}

int main()
{
    int d;
    d = max(44,8,16);
    
    if (d==a) {
        printf("a");
    }
    
    else if (d==b) {
        printf("b");
    }
    
    else {
        printf("c");
    }
}

It just shows me "c". Nothing else. What should I write in if functions in order to see "a", "b" and "c" characters according to return values in "max" function?

I want to keep max function as it is. So is it possible to do such a thing?

Thanks in advance..


Solution

  • You didn't assign any values to a, b, and c. And since they're globals they're implicitly initialized to 0. Note also that these globals are not the same as the parameters to max with the same name. The paramaters mask the globals.

    Move the globals into main and assign them values, then pass the variables to max.

    int main()
    {
        int a=48, b=8, c=16;
        int d;
        d = max(a,b,c);
        ...