TransWikia.com

How to declare a function using assignment operator?

Stack Overflow Asked by Legendrary Saiyan on December 27, 2021

This is my code. Every time I try to compile it, it gives me this error
expected primary-expression before ‘float’ at line 3

#include<iostream>
using namespace std;
auto fun = (float x){
    return 1/(1-x);
};
int main(){
    auto x=fun(0.5);
    cout<<x;
    return 0;
}

2 Answers

auto fun = [](float x){
    return 1/(1-x);
};

Answered by bipll on December 27, 2021

With the assignment operator (i.e., =) I can think of a lambda instead of a function:

auto fun = [](float x){
    return 1/(1-x);
};

That is, just by adding empty square brackets (i.e., [], which corresponds to the lambda capture list) before the parameter list, turns the code following the = into a lambda expression.

Technically, the = above isn't really the assignment operator. It just belongs to the syntax of copy initialization.

Answered by ネロク on December 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP