Home > Enterprise >  Error in function that returns a struct in c: expected identifier or '(' before paramter
Error in function that returns a struct in c: expected identifier or '(' before paramter

Time:10-06

I am new to c, and I'm trying to make a function that takes two parameters of type double as input, and returns a struct containing each parameter as members called "real" and imaginary. The error I am getting is:

error: expected identifier or ‘(’ before ‘double

The error is pointing to the line in which I define the function. I am aware that there are other posts covering this same error, but as far as I can tell, this is not the same issue as in those (and apologies if it is).

Here is my code:

#include <stdio.h>

int main(void) {
    return 0;
}

struct make_complex(double real_input, double imaginary_input) {

    struct complex {
        double real;
        double imaginary;
    } complex_output = {real_input, imaginary_input};

    return complex_output; 
}

I eventually want to call the make_complex function in main, but I have simplified main completely as to eliminate any other source of error. I have tried declaring the make_complex function before the function definition like so:

struct make_complex(double real_input, double imaginary_input);

This didn't work. Ideas?

Thanks for your time.

CodePudding user response:

In this function declaration

struct make_complex(double real_input, double imaginary_input) {

the compiler considers this line as a declaration of a structure with the name make_complex.

You need to define the structure complex before the function declaration as for example

struct complex {
    double real;
    double imaginary;
};

struct complex make_complex(double real_input, double imaginary_input) {

    struct complex complex_output = {real_input, imaginary_input};

    return complex_output; 
}

In C you even may define the structure in the declaration of the function return type

struct complex { double real; double imaginary; }
make_complex(double real_input, double imaginary_input) {
    struct complex complex_output = {real_input, imaginary_input};

    return complex_output; 
}

though it is not a good idea.:)

CodePudding user response:

The return type of the function needs to includes the structure type, not just struct. And you should define the structure type outside the function so it can be referenced in the callers.

#include <stdio.h>

struct complex {
    double real;
    double imaginary;
};

int main(void) {
    return 0;
}

struct complex make_complex(double real_input, double imaginary_input) {
    struct complex complex_output = {real_input, imaginary_input};
    return complex_output; 
}
  • Related