TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: CLIFF RHODES
from: RICK ARDING
date: 1997-03-27 07:08:00
subject: THINGS

-=> Quoting Cliff Rhodes to Rick Arding <=-
 --> 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,'\@'};
 CR> 
 CR> struct Thing {
 CR> int  Across, Down;
 CR> char Thingchar;
 CR> }
 CR> 
Sheesh, why didn't I try that
 CR> Thing You = { 1, 1, '\@' };  // In C++, the struct is not required
 
 CR> You don't need the dummy. You're passing a pointer so you must 
 CR> dereference it properly. You cannot use the '.' operator directly on a
 CR> pointer. You could do (*T).Across, etc. but C/C++ provides an operator
 CR> to do this more smoothly. T->Across.
 CR> 
 CR> void ShowThing(Thing *T)  // Return unnecessary so use void
 CR> {                         // Also, in C++ struct not required
 CR> gotoxy(T->Across, T->Down);  // Use -> operator to dereference
 CR> pointer putch(T->ThingChar);
 CR> }
 CR> 
 CR> 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.
 CR> 
 CR> Ah, but the idiosyncracies are where the magic lies. As a matter of
 CR> fact, you should make ShowThing a member of Thing, this being C++ and
 CR> all. Also add a constructor to initialize a Thing. That makes life
 CR> even  easier:
 CR> 
 CR> struct Thing {
 CR> int  Across, Down;
 CR> char ThingChar;
 CR> // Constructor
 CR> Thing(int a, int d, char c) { Across = a; Down = d; ThingChar = c; }
 CR> // ShowThing() member
 CR> void ShowThing(void) { gotoxy(Across, Down); putch(ThingChar); }
 CR> };
I've experimented a little with OOP.  I have trouble understanding
constructors and destructors so I leave them out.  I understand if you
do this then C++ add them.
When I define ShowThing don't I need to use a :: symbol or something, or
is it something that is not necessary?
 CR> 
 CR> int main(void)
 CR> {
 CR> Thing You(1, 1, '\@');
 CR> 
 CR> You.ShowThing();
 CR> 
 CR> return 0;
Thank you very much.  I'm going to work with this. Any other people I
talk to about C, tell me not to pass structures, just the fields from
the struct.  Seemed like a waste not to pass the whole structure.
Again thanks.  Your explanation was very clear.
... If it ain't DATA, then it MUST be code
___ Blue Wave/QWK v2.20 [NR]
--- FLAME v1.1
---------------
* Origin: 24th Street Exchange * A BBS Since 1983 * 916.448.2483 (1:203/52)

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™.