Thread: A function returns a structure

  1. #1
    Registered User
    Join Date
    Oct 2010
    Posts
    16

    A function returns a structure

    Hi, everyone! Is it safe to let a function return a structure type? For example, which function is better in practice in the example below?

    Thanks in advance!

    Code:
    #include <stdio.h>
    
    struct abc {
      int i;
      float f;
    };
    
    static struct abc f1 (int, float);
    static void f2 (struct abc *, int, float);
    
    struct abc f1 (int i, float f) {
      struct abc a;
      a.i = i;
      a.f = f;
      return a;
    }
    
    void f2 (struct abc *a, int i, float f) {
      a->i = i;
      a->f = f;
    }
    
    int main (void) {
      int i = 10;
      float f = 12.3;
      struct abc a, b;
      a = f1 (i, f);
      f2 (&b, i, f);
      printf("a: %3d %5.2f\n", a.i, a.f);
      printf("b: %3d %5.2f\n", b.i, b.f);
      return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    >> Is it safe to let a function return a structure type?
    Yes.
    If the size of struct is big, passing by value and returning might be expensive.

  3. #3
    Registered User
    Join Date
    Oct 2010
    Posts
    16
    Thanks!
    Does it mean that a function that returns a structure ACTUALLY returns the values of its every member?

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Yes, just like any other data type. Typically you're better off passing a pointer to the structure you want and just filling it inside the function, or, dynamically allocating the structure inside the function and returning a pointer to it. But yes, you can return an actual structure.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem Passing Structure Reference To Function
    By soj0mq3 in forum C Programming
    Replies: 9
    Last Post: 04-24-2010, 10:27 AM
  2. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  3. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  4. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM
  5. Tab Controls - API
    By -KEN- in forum Windows Programming
    Replies: 7
    Last Post: 06-02-2002, 09:44 AM