-1

when i am running below the code i am getting error but the same code run without making the function larger() code runs well. The code main purpose is to find largest of four number.

`code:

#include <iostream>
using namespace std;

int main(){
    int a,b,c,d,z,;
    int larger(a,b,c,d){
    return  a * (a >= b) * (a >= c) * (a >= d) + 
            b * (b >  a) * (b >= c) * (b >= d) + 
            c * (c >  a) * (c >  b) * (c >= d) + 
            d * (d >  a) * (d >  b) * (d >  c) ; 

    }

    z = larger(2,10,12,5);
    cout<<z;``


    return 0;
}
  • 2
    C++ doesn't allow nested functions. You might want to consider [lambda expressions](https://en.cppreference.com/w/cpp/language/lambda) if you don't want to write a stand-alone function. – Some programmer dude Oct 22 '20 at 08:45
  • And once you've learn the lesson from this assignment or exercise then use [`std::max`](https://en.cppreference.com/w/cpp/algorithm/max) instead of your own function. As in `z = std::max({ a, b, c, d });` – Some programmer dude Oct 22 '20 at 09:03

1 Answers1

0

I guess this is only an exercise otherwise you might have a look at std::max. However, there two major issues with your program:

  • you cannot define larger in main. If you want larger to be defined inside of main you have to use a lamda function, as suggested by @Some programmer dude in the comments.
  • when passing parameters to a function, c++ requires a type specifier. If you fix this, then the expression list treated as compund expression in initializer error goes away. See this question.

Here is working code:

#include <iostream>
using namespace std;

int larger(const int a, const int b, const int c, const int d){
return  a * (a >= b) * (a >= c) * (a >= d) + 
        b * (b >  a) * (b >= c) * (b >= d) + 
        c * (c >  a) * (c >  b) * (c >= d) + 
        d * (d >  a) * (d >  b) * (d >  c) ; 

}

int main(){

    int z = larger(2,10,12,5);
    cout<<z;

    return 0;
}

Live demo: godbolt

If you want to use a lambda function, this is the way to go:

#include <iostream>
using namespace std;

int main(){

    // define a lambda function
    auto larger = [](const int a, const int b, const int c, const int d) -> int {
        return  a * (a >= b) * (a >= c) * (a >= d) + 
                b * (b >  a) * (b >= c) * (b >= d) + 
                c * (c >  a) * (c >  b) * (c >= d) + 
                d * (d >  a) * (d >  b) * (d >  c) ; 
    };

    int z = larger(2,10,12,5);
    cout<<z;

    return 0;
}

Live demo: godbolt

As a remark, using using namespace std is typically not considered good paractice. See this question.

StefanKssmr
  • 1,196
  • 9
  • 16