TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: RICK ARDING
from: CLIFF RHODES
date: 1997-03-24 22:55:00
subject: Things

--> Rick Arding wrote to All  <--
 
RA>I was wondering what is the right way to pass a structure to a
RA>subroutine.  I fiddled and fiddled and the below example works, but
RA>it looks, well redundant.
RA>
RA>
RA>THE STRUCTURE
RA>struct Thing You = {1,1,'\@'};
 
struct Thing {
  int  Across, Down;
  char Thingchar;
}
 
Thing You = { 1, 1, '\@' };  // In C++, the struct is not required
 
RA>int ShowThing(struct Thing *T)
RA> {
RA>    struct Thing TT;            /*CAN'T DEAL WITH THE PASSED STRUC*/
RA>    TT=*T;                      /*SO I HAVE TO USE A DUMMY ONE    */
RA> gotoxy(TT.Across,TT.Down);
RA> putch(TT.ThingChar);
RA> *T=TT;
RA>    return(1);                  /*THEN I COPY THE DUMMY TO *T    */
RA>
RA>    }
You don't need the dummy. You're passing a pointer so you must 
dereference it properly. You cannot use the '.' operator directly on a 
pointer. You could do (*T).Across, etc. but C/C++ provides an operator 
to do this more smoothly. T->Across.
 
void ShowThing(Thing *T)  // Return unnecessary so use void
{                         // Also, in C++ struct not required
  gotoxy(T->Across, T->Down);  // Use -> operator to dereference pointer
  putch(T->ThingChar);
}
 
Now that's better!
RA>Is there a more logical way to do this?  Sometimes I think C just
RA>isn't worth the effort, with all of its little idiosyncrasies.
 
Ah, but the idiosyncracies are where the magic lies. As a matter of
fact, you should make ShowThing a member of Thing, this being C++ and
all. Also add a constructor to initialize a Thing. That makes life even 
easier:
 
struct Thing {
  int  Across, Down;
  char ThingChar;
  // Constructor
  Thing(int a, int d, char c) { Across = a; Down = d; ThingChar = c; } 
  // ShowThing() member
  void ShowThing(void) { gotoxy(Across, Down); putch(ThingChar); }
};
 
int main(void)
{
   Thing You(1, 1, '\@');
 
   You.ShowThing();
 
   return 0;
}
 
X CMPQwk 1.42 1692 XProofread carefully to see if you any words out.
--- Maximus/2 3.01
---------------
* Origin: COMM Port OS/2 juge.com 204.89.247.1 (281) 980-9671 (1:106/2000)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.