3

I want to create a structure called CarSpeed it has 4 int FR,FL,BR,BL (FrontRight,..) ; and i would like to create a function that returns this structure :

ActualSpeed Readspeed(void)
{
   code to read the speed of the car(already done)
}

Can someone help me define a function that returns this structure ? only the way how I should define it, the usual C way doesnt work :

typedefstruct CarSpeed{...}

and then

CarSpeed ActualSpeed;
ActualSpeed Readspeed(void){.. }

2 Answers 2

3

Since you're (probably) using a C++ compiler, it's usually easier to declare structures like this:

struct CarSpeed
{
    int fr, fl, br, bl;
};

(Note that there's no need for typedef.)

You can then return an instance of it directly from your function:

CarSpeed ReadSpeed()
{
    CarSpeed data;

    data.fr = ...;
    data.fl = ...;
    data.br = ...;
    data.bl = ...;

    return data;
}

You can call it from another function like this:

CarSpeed speed = ReadSpeed();

That will copy the contents of the structure into an object called speed. In this example, it's an 8 byte structure so it's a non-trivial copy. That shouldn't be a big problem unless you're calling it very frequently though.

As noted in another answer, using a pointer (or a reference) can be more efficient if necessary.

2
  • Thx, but I get this error : nMotSet-Final:12: error: 'CarSpeed' does not name a type , maybe i should include the variable creation part in a .h file ?
    – Mehdi
    Commented Aug 27, 2015 at 15:00
  • If you mean the struct declaration, then it's essential to put that in a header file if you intend to call ReadSpeed() from a different file. Commented Aug 27, 2015 at 15:09
1

I would recommend to use pointers, it's faster and has the same result.

Something like this (disclaimer - I did not compile it):

typedef struct {
   int a;
   int b;
} pair;


int init_pair(pair *ptr) {
   if (!ptr)
      return -1;
   ptr->a = 6;
   ptr->b = 9;
   return 0;
}

int do_something() {
   pair mypair;
   return init_pair(&mypair);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.