Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

returning struct

Status
Not open for further replies.

troye

Technical User
May 16, 2003
21
MY
I have a function that is to return an entire struct. How would I declare the function? What do I use instead of the "void"?

Ex.

void get_data(void)
{
struct emp boss;
printf("Enter Employer's Name, Salary: ");
scanf("%s %f", &boss.empname, &boss.salary);
get_date();
hired.yy = boss.hired.yy;
hired.mm = boss.hired.mm;
hired.dd = boss.hired.dd;

return boss;
}
 
You need to define your function as:

struct emp get_date(void)
 
If working in C++ mode you can do like this:

emp get_data(void)
...

Ion Filipski
1c.bmp
 
If working in C++ then it makes better sense to do this:
Code:
   void get_date(emp& value) {
      // ... do the stuff you need
      return;
   }
   // and use it
   int main() {
      emp v;
      get_date(v);
      return 0;
   }
rather than:
Code:
   emp get_date(void) {
      emp ret;
      // ... do the stuff you need
      return ret;
   }
   // and use it
   int main() {
      emp v = get_date();
      return 0;
   }
Why?
The second example (unless your compiler is really smart) involves copying the members of the structure into a
temporary emp which is then copied into v. If emp has complex members which are classes, this may involve quite an overhead.
The first example only uses one emp[/green] and will execute much faster.
Just a hint, just a thought.
(There is also the consideration that the first example allows the function to be changed to return a value which indicates that it was successful or otherwise).

Roger J Coult
Allied Laboratory Services Limited
Grimsby, UK
 
Code:
struct emp *get_data(void) {
struct emp *new = NULL;


          new = malloc(sizeof(struct emp));
          if (new) {
              printf("Enter Employer's Name, Salary: ");
              scanf("%s %f", new->empname, new->salary);
              get_date();
              //other work here
              return new;
           }
          printf("ERROR: malloc(), out of memory??\n");
          return NULL;
          //or exit
}



 
marsd, how does variable new work with comments //?

Ion Filipski
1c.bmp
 
> how does variable new work with comments //?
Either
A C compiler extension to allow C++ style comments
A C99 compatible compiler.

--
 
Works fine with gcc , but point taken.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top