8 years, 6 months ago.

return multiple values from a function

Hi,

I'm trying to write a function which would return more than one value. I have two examples that work - ether by defining the function type by a struct or by passing the parameters as pointers.

Now when I put the function definitions into a class in .h and .cpp files I get compilation errors.

Here is the code of the testing example. Any ideas what's wrong? Thank you Juerg

main:

  1. include "mbed.h"
  2. include "helper.h"

int main() { Bar dunno = funct();

printf("reading: %d %d\r\n", dunno.x,dunno.y);

int x,y; funct2(&x, &y); printf("reading: %d %d\r\n", x,y); return 0; }

header file:

  1. include <mbed.h>

class helper { public: struct Bar; struct Bar funct(); void funct2(int *x, int *y); };

cpp file:

  1. include <mbed.h>
  2. include "helper.h"

struct Bar{ int x; int y; };

Bar funct(){ struct Bar result; result.x = 10; result.y = 20; return result; }

void funct2(int *x, int *y){ /* dereferencing and setting */

  • x = 1;
  • y = 2; }

Please use <<code>> and <</code>> around your code, now it is very hard to read. Also which compilations errors do you get?

posted by Erik - 23 Oct 2015

Sorry, didn't know. So here the code once again:

//main 
#include "mbed.h"
#include "helper.h"

int main()
{
    Bar dunno = funct();
    printf("reading: %d   %d\r\n", dunno.x,dunno.y);
    int x,y;
    funct2(&x, &y);
    printf("reading: %d   %d\r\n", x,y);
    return 0;
}
// helper.h
#include <mbed.h>
class helper
{
public:
struct Bar;
struct Bar funct();
void funct2(int *x, int *y);
};

//helper.cpp
#include <mbed.h>
#include "helper.h"

struct helper::Bar{
    int x;
    int y;
};

struct helper::Bar helper::funct(){
    struct helper::Bar result;
    result.x = 10;
    result.y = 20;
    return result;
}

void helper::funct2(int *x, int *y){
    /* dereferencing and setting */
    *x  = 1;
    *y  = 2;
}

and these are the errors in main. No errors indicated in helper files.

Error: Identifier "Bar" is undefined in "main.cpp", Line: 8, Col: 6 Error: Expected a ";" in "main.cpp", Line: 8, Col: 10 Error: Identifier "dunno" is undefined in "main.cpp", Line: 10, Col: 37 Error: Identifier "funct2" is undefined in "main.cpp", Line: 12, Col: 6

posted by juerg hofer 26 Oct 2015

1 Answer

8 years, 6 months ago.

As erik said, please use <<code>> and <</code>> to make things readable.

One obvious issue, when defining members of a class you need to indicate that they are members of a class. In your helper.cpp file you need to put the class name in front of the function names.

Bar helper::funct(){ struct Bar result; result.x = 10; result.y = 20; return result; }

void helper::funct2(int *x, int *y){ /* dereferencing and setting */
*x = 1;
*y = 2;
}