Question about pointers?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • kazack

    Question about pointers?

    I am under the the impression that a variable is what is stored in a memory
    address and a pointer is the memory address of the variable?

    I was looking to use a function that does not return a value void
    whatever(whatev er) and not have a variable global but in main and change the
    value in the void whatever function.

    using namespace std;
    void whatever(int);

    int main()
    {
    int test;
    test = 1;
    whatever(test);
    return 1;
    }
    void whatever(int testing)
    {
    &test = testing
    // The above line I am unsure of how to exactly do it.
    //what would I need to change in order to change the
    //value of test in main though the whatever function
    //without actually having to return a value.
    }
    Thank you,
    Shawn Mulligan


  • Artie Gold

    #2
    Re: Question about pointers?

    kazack wrote:[color=blue]
    > I am under the the impression that a variable is what is stored in a memory
    > address and a pointer is the memory address of the variable?
    >
    > I was looking to use a function that does not return a value void
    > whatever(whatev er) and not have a variable global but in main and change the
    > value in the void whatever function.
    >
    > using namespace std;
    > void whatever(int);
    >
    > int main()
    > {
    > int test;
    > test = 1;
    > whatever(test);
    > return 1;
    > }
    > void whatever(int testing)[/color]

    Just make the above:
    void whatever(int& testing)

    and any changes made to `testing' will be reflected in the caller.
    [color=blue]
    > {
    > &test = testing
    > // The above line I am unsure of how to exactly do it.
    > //what would I need to change in order to change the
    > //value of test in main though the whatever function
    > //without actually having to return a value.
    > }[/color]

    ....and *please* look up `reference' in your favorite C++ documentation.

    HTH,
    --ag
    --
    Artie Gold -- Austin, Texas
    Oh, for the good old days of regular old SPAM.

    Comment

    • Rolf Magnus

      #3
      Re: Question about pointers?

      kazack wrote:
      [color=blue]
      > I am under the the impression that a variable is what is stored in a
      > memory address and a pointer is the memory address of the variable?[/color]

      More or less. You could rather say that a variable must be somewhere in
      memory, and every piece of memory has an address. A pointer can hold
      such an address.
      [color=blue]
      > I was looking to use a function that does not return a value void
      > whatever(whatev er) and not have a variable global but in main and
      > change the value in the void whatever function.
      >
      > using namespace std;
      > void whatever(int);
      >
      > int main()
      > {
      > int test;
      > test = 1;
      > whatever(test);
      > return 1;
      > }
      > void whatever(int testing)
      > {
      > &test = testing
      > // The above line I am unsure of how to exactly do it.
      > //what would I need to change in order to change the
      > //value of test in main though the whatever function
      > //without actually having to return a value.[/color]

      You cannot change the variable 'test' from main this way, because it is
      passed to the function by value, i.e. a copy of it is made, and your
      whatever() function only sees that copy. Any modification to the
      'testing' parameter will only modify the local copy in the function.
      For doing what you want to do, you need to pass by reference, i.e.:

      void whatever(int& testing)
      {
      //do some changes to testing
      }

      This way, testing will be a reference, which means that it is just
      another name for the variable 'test' from main(), so any change to
      'testing' in whatever() will result in a changed 'test' in main().


      Comment

      • kazack

        #4
        Re: Question about pointers?

        Is there anyway possible also with the use of pointers to reference a
        variable, that is not global and is not passed directly into a function?

        Or does it have to be global or passed?

        Thank You,
        Shawn Mulligan


        Comment

        • Mike Wahler

          #5
          Re: Question about pointers?


          "kazack" <kazack@talon.n et> wrote in message
          news:IpXob.6207 $Bv6.1911152@ne ws1.epix.net...[color=blue]
          > Is there anyway possible also with the use of pointers to reference a
          > variable, that is not global and is not passed directly into a function?[/color]

          Yes.

          #include <iostream>

          void changeit(int *arg)
          {
          *arg = 42;
          }

          int main()
          {
          int i = 0;
          std::cout << i << '\n'; /* prints 0 */
          changeit(&i)
          std::cout << i << '\n'; /* prints 42 */
          return 0;
          }

          This is the way it's done in C (and can also be done this
          way in C++, although references are more 'idiomatic'
          in C++).
          [color=blue]
          >
          > Or does it have to be global or passed?[/color]

          All functions have access to a 'global' object.
          This is the reason why such 'globals' should be
          avoided if possible, it leaves open the possibility
          of a function changing something which it should
          not.


          -Mike


          Comment

          • Jon Bell

            #6
            Re: Question about pointers?

            In article <7yWob.6205$Bv6 .1910855@news1. epix.net>,
            kazack <kazack@talon.n et> wrote:[color=blue]
            >I am under the the impression that a variable is what is stored in a memory
            >address and a pointer is the memory address of the variable?[/color]

            I would say that a variable is a memory location whose contents can be
            changed (unless it is declared as const), and a pointer is a variable that
            contains a memory address. That address is usually the address of another
            variable (or at least it's intended to be).

            --
            Jon Bell <jtbellap8@pres by.edu> Presbyterian College
            Dept. of Physics and Computer Science Clinton, South Carolina USA

            Comment

            • Evan

              #7
              Re: Question about pointers?

              "kazack" <kazack@talon.n et> wrote in message news:<IpXob.620 7$Bv6.1911152@n ews1.epix.net>. ..[color=blue]
              > Is there anyway possible also with the use of pointers to reference a
              > variable, that is not global and is not passed directly into a function?[/color]

              You have to pass it in. If a variable is local to a function and you
              call another function, the only way to access that variable is by
              passing it in by reference or it's address as a pointer.



              Actually this isn't exactly true... you can store the address in an
              external pointer, a la:

              int *bad_example;

              int main() {
              int value_to_change = 10;
              bad_example = &value_to_chang e;
              foo();
              cout << value_to_change ; // Should print 20
              }

              void foo() {
              *bad_example = 20;
              }

              But you *do* need a global variable. And at any rate, the above
              example is bad bad and bad.

              It violates good design rules left and right. Global variables are
              shunned in general, and using one to change a local variable is even
              worse. Generally what a function does should be clear from it's name
              and the parameters; foo() above doesn't make clear what it is doing at
              all. So if your function needs to change another value, either pass in
              the value as a reference parameter (or pointer; some people prefer
              this for some good reasons, though syntactically references are
              clearer) or return it.

              Comment

              • kazack

                #8
                Re: Question about pointers?

                Wow I should of just stuck with VB. I am learning alot between the book I
                am using and you guys here.

                The sample program I am writing from the book which I have working is to
                JUST read i a file with three sides to a triangle, multiple triangle
                dimensions listed, and tell what type of triangle it is if it is a valid
                triangle. Well I got that done with no problem but I like pushing the
                envelope a little bit more than just doing what they ask. I have added the
                ability to check for file existance, which was OS dependant until I was told
                about cerrno header file. Big help, I didn't even know this existed, it's
                not in my book anywhere, a matter of fact in none of my books I have and I
                have 3 c++ books and 2 c books. Now I am learning about pointers 2 chapters
                ahead of time to accomplish what I need done. I need to call a function
                from within a function from within a function and I did not feel like having
                to pass variables from the first function to the second function so I can
                work with it in the third. Is this the standard way to do things? Or is
                this bad coding habits? I am teaching myself here as you guys can prolly
                tell by my questions i am and have asked?

                Is it good or bad to pass a variable into a function just to beable to pass
                it into another function so it can be used?

                Thank you guys again for your help,
                Shawn Mulligan

                "Evan" <eed132@psu.edu > wrote in message
                news:3f25c666.0 311011835.5d703 4b8@posting.goo gle.com...[color=blue]
                > "kazack" <kazack@talon.n et> wrote in message[/color]
                news:<IpXob.620 7$Bv6.1911152@n ews1.epix.net>. ..[color=blue][color=green]
                > > Is there anyway possible also with the use of pointers to reference a
                > > variable, that is not global and is not passed directly into a function?[/color]
                >
                > You have to pass it in. If a variable is local to a function and you
                > call another function, the only way to access that variable is by
                > passing it in by reference or it's address as a pointer.
                >
                >
                >
                > Actually this isn't exactly true... you can store the address in an
                > external pointer, a la:
                >
                > int *bad_example;
                >
                > int main() {
                > int value_to_change = 10;
                > bad_example = &value_to_chang e;
                > foo();
                > cout << value_to_change ; // Should print 20
                > }
                >
                > void foo() {
                > *bad_example = 20;
                > }
                >
                > But you *do* need a global variable. And at any rate, the above
                > example is bad bad and bad.
                >
                > It violates good design rules left and right. Global variables are
                > shunned in general, and using one to change a local variable is even
                > worse. Generally what a function does should be clear from it's name
                > and the parameters; foo() above doesn't make clear what it is doing at
                > all. So if your function needs to change another value, either pass in
                > the value as a reference parameter (or pointer; some people prefer
                > this for some good reasons, though syntactically references are
                > clearer) or return it.[/color]


                Comment

                • Charles LaCour

                  #9
                  Re: Question about pointers?


                  "kazack" <kazack@talon.n et> wrote in message
                  news:SU_ob.6213 $Bv6.1912485@ne ws1.epix.net...[color=blue]
                  > Wow I should of just stuck with VB. I am learning alot between the book I
                  > am using and you guys here.
                  >
                  > The sample program I am writing from the book which I have working is to
                  > JUST read i a file with three sides to a triangle, multiple triangle
                  > dimensions listed, and tell what type of triangle it is if it is a valid
                  > triangle. Well I got that done with no problem but I like pushing the
                  > envelope a little bit more than just doing what they ask. I have added[/color]
                  the[color=blue]
                  > ability to check for file existance, which was OS dependant until I was[/color]
                  told[color=blue]
                  > about cerrno header file. Big help, I didn't even know this existed, it's
                  > not in my book anywhere, a matter of fact in none of my books I have and I
                  > have 3 c++ books and 2 c books. Now I am learning about pointers 2[/color]
                  chapters[color=blue]
                  > ahead of time to accomplish what I need done. I need to call a function
                  > from within a function from within a function and I did not feel like[/color]
                  having[color=blue]
                  > to pass variables from the first function to the second function so I can
                  > work with it in the third. Is this the standard way to do things? Or is
                  > this bad coding habits? I am teaching myself here as you guys can prolly
                  > tell by my questions i am and have asked?
                  >
                  > Is it good or bad to pass a variable into a function just to beable to[/color]
                  pass[color=blue]
                  > it into another function so it can be used?
                  >
                  > Thank you guys again for your help,
                  > Shawn Mulligan[/color]

                  The program you are writing doesn't sound particularly complicated, so I'm
                  guessing that it is not unreasonably long. Why don't you post your code and
                  maybe someone can point out any flaws in your reasoning. Yes, it can be
                  annoying to pass a value from one function to another, but it's not bad
                  coding.

                  By the way, to the best of my knowledge, VB won't allow you to get the
                  address of a variable that is inside another function, so I don't see how
                  staying with VB would have helped you.
                  [color=blue]
                  >
                  > "Evan" <eed132@psu.edu > wrote in message
                  > news:3f25c666.0 311011835.5d703 4b8@posting.goo gle.com...[color=green]
                  > > "kazack" <kazack@talon.n et> wrote in message[/color]
                  > news:<IpXob.620 7$Bv6.1911152@n ews1.epix.net>. ..[color=green][color=darkred]
                  > > > Is there anyway possible also with the use of pointers to reference a
                  > > > variable, that is not global and is not passed directly into a[/color][/color][/color]
                  function?[color=blue][color=green]
                  > >
                  > > You have to pass it in. If a variable is local to a function and you
                  > > call another function, the only way to access that variable is by
                  > > passing it in by reference or it's address as a pointer.
                  > >
                  > >
                  > >
                  > > Actually this isn't exactly true... you can store the address in an
                  > > external pointer, a la:
                  > >
                  > > int *bad_example;
                  > >
                  > > int main() {
                  > > int value_to_change = 10;
                  > > bad_example = &value_to_chang e;
                  > > foo();
                  > > cout << value_to_change ; // Should print 20
                  > > }
                  > >
                  > > void foo() {
                  > > *bad_example = 20;
                  > > }
                  > >
                  > > But you *do* need a global variable. And at any rate, the above
                  > > example is bad bad and bad.
                  > >
                  > > It violates good design rules left and right. Global variables are
                  > > shunned in general, and using one to change a local variable is even
                  > > worse. Generally what a function does should be clear from it's name
                  > > and the parameters; foo() above doesn't make clear what it is doing at
                  > > all. So if your function needs to change another value, either pass in
                  > > the value as a reference parameter (or pointer; some people prefer
                  > > this for some good reasons, though syntactically references are
                  > > clearer) or return it.[/color]
                  >
                  >[/color]


                  Comment

                  • Evan

                    #10
                    Re: Question about pointers?

                    "kazack" <kazack@talon.n et> wrote in message news:<SU_ob.621 3$Bv6.1912485@n ews1.epix.net>. ..[color=blue]
                    > The sample program I am writing from the book which I have working is to
                    > JUST read i a file with three sides to a triangle, multiple triangle
                    > dimensions listed, and tell what type of triangle it is if it is a valid
                    > triangle. Well I got that done with no problem but I like pushing the
                    > envelope a little bit more than just doing what they ask.[/color]

                    This is good.
                    [color=blue]
                    > I have added the
                    > ability to check for file existance, which was OS dependant until I was told
                    > about cerrno header file.[/color]

                    cerrno? What are you doing to open files? This is a header inherited
                    from C that shouldn't be necessary unless I'm missing something.
                    [color=blue]
                    > Big help, I didn't even know this existed, it's
                    > not in my book anywhere, a matter of fact in none of my books I have and I
                    > have 3 c++ books and 2 c books.[/color]

                    This is not a surprise; even in Stroustrup I can't seem to find
                    mention other than in the list of standard headers.
                    [color=blue]
                    > Now I am learning about pointers 2 chapters
                    > ahead of time to accomplish what I need done. I need to call a function
                    > from within a function from within a function and I did not feel like having
                    > to pass variables from the first function to the second function so I can
                    > work with it in the third. Is this the standard way to do things? Or is
                    > this bad coding habits?[/color]

                    It depends on the functions; I'd have to see your specific example to
                    give you my opinion. However, there are times when a function doesn't
                    do anything with one or more of its argument except pass it to another
                    function.
                    [color=blue]
                    > I am teaching myself here as you guys can prolly
                    > tell by my questions i am and have asked?[/color]

                    That's what we're here for. If we weren't learning there'd be no
                    purpose for the newsgroup. :-p

                    Comment

                    • kazack

                      #11
                      Re: Question about pointers?

                      Welp after writing and rewriting I hope I have code that is 100% standard
                      with the exception of the void fileexistcheck( filename) that is OS
                      dependant. I hope the rest of it is totally standard. I started out with
                      value returning functions, then switched in mid gear to change it all to
                      void functions and do as much as I could with pointers. So I would like to
                      have this code critiqued. I would like to know for my own benefit, Is it
                      better to have a value returning function or to pass a pointer?

                      Welp below here is the code in full. I do not have it documented although
                      the names of the variables and functions are self
                      explanatory.----------------------------------------------------------------
                      ----------------------------------------------------------------------------
                      --------------------------------------------------------------
                      #include <iostream>
                      #include <io.h>
                      #include <cstring>
                      #include <string>
                      #include <fstream>
                      #include <cctype>
                      using namespace std;

                      void selectfilename( string&);
                      void fileexistcheck( string, bool&);
                      void readdata(string );
                      void NotValid(int, int, int);
                      void Equal(int,int,i nt);
                      void Isos(int,int,in t);
                      void triangle(int,in t,int,int);
                      void createfile(stri ng);

                      enum Triangles{Scale ne,Isosceles,Eq ualateral,Inval id,Hold};
                      Triangles Entered = Hold;

                      int main()
                      {
                      string filename;
                      char yeahneah;
                      bool exists;
                      selectfilename( filename);
                      fileexistcheck( filename,exists );
                      if (exists == true)
                      {
                      readdata(filena me);
                      }
                      else
                      {
                      cout << endl << filename << " does not exist." << endl;
                      cout << "Would you like to select a different filename? (Y/N): ";
                      cin >> yeahneah;
                      if (toupper(yeahne ah) == 'Y')
                      {
                      main();
                      }
                      else
                      {
                      cout << "Would you like to create this file? (Y/N):";
                      cin >> yeahneah;
                      if (toupper(yeahne ah)=='Y')
                      {
                      createfile(file name);
                      readdata(filena me);
                      }
                      }
                      }
                      return 0;
                      }

                      void selectfilename( string& filename)
                      {
                      cout << "Please Enter The Data File You Would Like To Use: ";
                      cin >> filename;
                      }


                      void fileexistcheck( string filename, bool& exists)
                      {
                      if ((_access(filen ame.c_str (),0))!=-1)
                      {
                      exists = true;
                      }
                      else
                      {
                      exists = false;
                      }
                      }





                      void readdata(string filename)
                      {
                      int sidea;
                      int sideb;
                      int sidec;

                      ifstream inData;
                      inData.open(fil ename.c_str());

                      inData >> sidea >> sideb >> sidec;

                      while(inData)
                      {

                      NotValid(sidea, sideb, sidec);
                      if (Entered == Invalid)
                      {
                      triangle(Entere d,sidea,sideb,s idec);
                      }
                      else
                      {
                      Equal(sidea,sid eb,sidec);
                      if (Entered == Equalateral)
                      {
                      triangle(Entere d,sidea,sideb,s idec);
                      }
                      else
                      {
                      Isos(sidea,side b,sidec);
                      if (Entered == Isosceles)
                      {
                      triangle(Entere d,sidea,sideb,s idec);
                      }
                      else
                      {
                      Entered = Scalene;
                      triangle(Entere d,sidea,sideb,s idec);
                      }
                      }
                      }
                      inData >> sidea >> sideb >> sidec;
                      }
                      inData.close();
                      }

                      void Isos(int sidea, int sideb, int sidec)
                      {
                      Entered = ((sidea == sideb) || (sideb==sidec) ||
                      (sidec==sidea)) ?Isosceles:Inva lid;
                      }

                      void NotValid(int sidea,int sideb,int sidec)
                      {
                      Entered = ((sidea + sideb > sidec) && (sideb + sidec > sidea) && (sidea +
                      sidec > sideb))?Hold:In valid;
                      }

                      void Equal(int sidea, int sideb, int sidec)
                      {
                      Entered = ((sidea == sideb) && (sideb==sidec) &&
                      (sidec==sidea)) ?Equalateral:Ho ld;
                      }

                      void triangle(int Entered,int sidea, int sideb, int sidec)
                      {

                      switch(Entered)
                      {
                      case 0 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
                      <<" makes this a Scalene Triangle"<<endl ; break;
                      case 1 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
                      <<" makes this an Isosceles Triangle"<<endl ; break;
                      case 2 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
                      <<" makes this an Equalateral Triangle"<<endl ; break;
                      case 3 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
                      <<" makes this an Invalid Triangle"<<endl ; break;
                      }
                      }


                      void createfile(stri ng filename)
                      {
                      char choice;
                      string sidea;
                      string sideb;
                      string sidec;

                      ofstream outData;




                      cout << "Please enter A to Add a triangle or Q to stop adding triangles to
                      this file: ";
                      cin >> choice;
                      while ((toupper(choic e) != 'A') && (toupper(choice ) != 'Q'))
                      {
                      cout << "Please enter A to Add a triangle or Q to stop adding triangles to
                      this file: ";
                      cin >> choice;
                      }

                      while (toupper(choice ) =='A')
                      {
                      outData.open(fi lename.c_str(), ios::app);
                      cout << "Enter Side 1 of this triangle: ";
                      cin >> sidea;
                      cout << endl << "Enter Side 2 of this triangle: ";
                      cin >> sideb;
                      cout << endl << "Enter Side 3 of this triangle: ";
                      cin >> sidec;
                      outData << sidea << " " << sideb << " " << sidec << endl;
                      outData.close() ;
                      cout << "Please enter A to Add a triangle or Q to stop adding triangles to
                      this file: ";
                      cin >> choice;
                      }
                      }
                      ----------------------------------------------------------------------------
                      ----------------------------------------------------------------------------
                      ----------------------
                      Thanks again for the time and patience with me and explaing to me the goods,
                      the bads and the uglys.
                      I know uglys is mispelled but I thought it looked good to go with the other
                      two.
                      "Charles LaCour" <YouDontKnowMe@ phantom.net> wrote in message
                      news:bM%ob.8578 2$vj2.28770@fed 1read06...[color=blue]
                      >
                      > "kazack" <kazack@talon.n et> wrote in message
                      > news:SU_ob.6213 $Bv6.1912485@ne ws1.epix.net...[color=green]
                      > > Wow I should of just stuck with VB. I am learning alot between the book[/color][/color]
                      I[color=blue][color=green]
                      > > am using and you guys here.
                      > >
                      > > The sample program I am writing from the book which I have working is to
                      > > JUST read i a file with three sides to a triangle, multiple triangle
                      > > dimensions listed, and tell what type of triangle it is if it is a valid
                      > > triangle. Well I got that done with no problem but I like pushing the
                      > > envelope a little bit more than just doing what they ask. I have added[/color]
                      > the[color=green]
                      > > ability to check for file existance, which was OS dependant until I was[/color]
                      > told[color=green]
                      > > about cerrno header file. Big help, I didn't even know this existed,[/color][/color]
                      it's[color=blue][color=green]
                      > > not in my book anywhere, a matter of fact in none of my books I have and[/color][/color]
                      I[color=blue][color=green]
                      > > have 3 c++ books and 2 c books. Now I am learning about pointers 2[/color]
                      > chapters[color=green]
                      > > ahead of time to accomplish what I need done. I need to call a function
                      > > from within a function from within a function and I did not feel like[/color]
                      > having[color=green]
                      > > to pass variables from the first function to the second function so I[/color][/color]
                      can[color=blue][color=green]
                      > > work with it in the third. Is this the standard way to do things? Or[/color][/color]
                      is[color=blue][color=green]
                      > > this bad coding habits? I am teaching myself here as you guys can[/color][/color]
                      prolly[color=blue][color=green]
                      > > tell by my questions i am and have asked?
                      > >
                      > > Is it good or bad to pass a variable into a function just to beable to[/color]
                      > pass[color=green]
                      > > it into another function so it can be used?
                      > >
                      > > Thank you guys again for your help,
                      > > Shawn Mulligan[/color]
                      >
                      > The program you are writing doesn't sound particularly complicated, so I'm
                      > guessing that it is not unreasonably long. Why don't you post your code[/color]
                      and[color=blue]
                      > maybe someone can point out any flaws in your reasoning. Yes, it can be
                      > annoying to pass a value from one function to another, but it's not bad
                      > coding.
                      >
                      > By the way, to the best of my knowledge, VB won't allow you to get the
                      > address of a variable that is inside another function, so I don't see how
                      > staying with VB would have helped you.
                      >[color=green]
                      > >
                      > > "Evan" <eed132@psu.edu > wrote in message
                      > > news:3f25c666.0 311011835.5d703 4b8@posting.goo gle.com...[color=darkred]
                      > > > "kazack" <kazack@talon.n et> wrote in message[/color]
                      > > news:<IpXob.620 7$Bv6.1911152@n ews1.epix.net>. ..[color=darkred]
                      > > > > Is there anyway possible also with the use of pointers to reference[/color][/color][/color]
                      a[color=blue][color=green][color=darkred]
                      > > > > variable, that is not global and is not passed directly into a[/color][/color]
                      > function?[color=green][color=darkred]
                      > > >
                      > > > You have to pass it in. If a variable is local to a function and you
                      > > > call another function, the only way to access that variable is by
                      > > > passing it in by reference or it's address as a pointer.
                      > > >
                      > > >
                      > > >
                      > > > Actually this isn't exactly true... you can store the address in an
                      > > > external pointer, a la:
                      > > >
                      > > > int *bad_example;
                      > > >
                      > > > int main() {
                      > > > int value_to_change = 10;
                      > > > bad_example = &value_to_chang e;
                      > > > foo();
                      > > > cout << value_to_change ; // Should print 20
                      > > > }
                      > > >
                      > > > void foo() {
                      > > > *bad_example = 20;
                      > > > }
                      > > >
                      > > > But you *do* need a global variable. And at any rate, the above
                      > > > example is bad bad and bad.
                      > > >
                      > > > It violates good design rules left and right. Global variables are
                      > > > shunned in general, and using one to change a local variable is even
                      > > > worse. Generally what a function does should be clear from it's name
                      > > > and the parameters; foo() above doesn't make clear what it is doing at
                      > > > all. So if your function needs to change another value, either pass in
                      > > > the value as a reference parameter (or pointer; some people prefer
                      > > > this for some good reasons, though syntactically references are
                      > > > clearer) or return it.[/color]
                      > >
                      > >[/color]
                      >
                      >[/color]


                      Comment

                      • Evan

                        #12
                        Re: Question about pointers?

                        "kazack" <kazack@talon.n et> wrote in message news:<DJ3pb.621 6$Bv6.1913396@n ews1.epix.net>. ..[color=blue]
                        > Welp after writing and rewriting I hope I have code that is 100% standard
                        > with the exception of the void fileexistcheck( filename) that is OS
                        > dependant. I hope the rest of it is totally standard.[/color]

                        Yes
                        [color=blue]
                        > I would like to know for my own benefit, Is it
                        > better to have a value returning function or to pass a pointer?[/color]

                        Almost always returning a value is preferable, at least IMO. See my
                        comments in code.

                        [color=blue]
                        > #include <iostream>
                        > #include <io.h>
                        > #include <cstring>
                        > #include <string>
                        > #include <fstream>
                        > #include <cctype>
                        > using namespace std;
                        >
                        > [Function prototypes omitted]
                        >
                        > enum Triangles{Scale ne,Isosceles,Eq ualateral,Inval id,Hold};
                        > Triangles Entered = Hold;
                        >
                        > int main()
                        > {
                        > string filename;
                        > char yeahneah;
                        > bool exists;
                        > selectfilename( filename);
                        > fileexistcheck( filename,exists );[/color]

                        Why oh why do you do this? :-p One of the reasons that some people
                        don't like reference passing (and one reason Java doesn't have it in
                        the sense C++ does, and one reason why C# requires the keyword ref in
                        the function call, as in fileexists(file name, ref exists)) is that it
                        is not apparent at all that the function changes the value of exists.
                        Returning the bool then saying

                        exists = fileexistcheck( filename);

                        is *much* more readable for anyone I've talked to. Passing values out
                        of functions in the way you did has uses in some cases, for instance
                        if you need two values returned (e.g. a pointer and a bool if the
                        pointer is valid), but I'd say change this. And if I were your boss
                        I'd say change it.
                        [color=blue]
                        > if (exists == true)[/color]

                        Plus, here you could say
                        if (fileexistcheck (filename) == true)
                        if you did that. You can compose function calls.
                        [color=blue]
                        > {
                        > readdata(filena me);
                        > }
                        > else
                        > {
                        > cout << endl << filename << " does not exist." << endl;
                        > cout << "Would you like to select a different filename? (Y/N): ";
                        > cin >> yeahneah;
                        > if (toupper(yeahne ah) == 'Y')
                        > {
                        > main();
                        > }
                        > else
                        > {
                        > cout << "Would you like to create this file? (Y/N):";
                        > cin >> yeahneah;
                        > if (toupper(yeahne ah)=='Y')
                        > {
                        > createfile(file name);
                        > readdata(filena me);
                        > }
                        > }
                        > }
                        > return 0;
                        > }
                        >
                        > void selectfilename( string& filename)
                        > {
                        > cout << "Please Enter The Data File You Would Like To Use: ";
                        > cin >> filename;
                        > }[/color]

                        Case in point of what I said earlier: before I got here I had a
                        comment after the declaration of filename in main that said "I assume
                        filename is initialized somewhere in here" because it was not clear at
                        all that selectfilename sets its argument to the filename.
                        [color=blue]
                        > void fileexistcheck( string filename, bool& exists)
                        > {
                        > if ((_access(filen ame.c_str (),0))!=-1)
                        > {
                        > exists = true;
                        > }
                        > else
                        > {
                        > exists = false;
                        > }
                        > }[/color]

                        Here you can just test to see if the fstream you attempt to open in
                        the next function is good. Like you have a while(inData) loop; this
                        will not run if the file does not exist and is not created (if you
                        want to stop creation you need to pass another argument to the
                        constructor). It's not entirely the same thing, but it's probably
                        acceptable.
                        [color=blue]
                        > void readdata(string filename)
                        > {
                        > int sidea;
                        > int sideb;
                        > int sidec;
                        >
                        > ifstream inData;
                        > inData.open(fil ename.c_str());
                        >
                        > inData >> sidea >> sideb >> sidec;
                        >
                        > while(inData)
                        > {
                        >
                        > NotValid(sidea, sideb, sidec);
                        > if (Entered == Invalid)
                        > {
                        > triangle(Entere d,sidea,sideb,s idec);[/color]

                        As the program is structured now, there is no need to pass Entered
                        since its global anyway.
                        [color=blue]
                        > }
                        > else
                        > {
                        > Equal(sidea,sid eb,sidec);
                        > if (Entered == Equalateral)
                        > {
                        > triangle(Entere d,sidea,sideb,s idec);
                        > }
                        > else
                        > {
                        > Isos(sidea,side b,sidec);
                        > if (Entered == Isosceles)
                        > {
                        > triangle(Entere d,sidea,sideb,s idec);
                        > }
                        > else
                        > {
                        > Entered = Scalene;
                        > triangle(Entere d,sidea,sideb,s idec);
                        > }
                        > }
                        > }
                        > inData >> sidea >> sideb >> sidec;
                        > }
                        > inData.close();
                        > }
                        >
                        > [Other functions omitted; no comments][/color]

                        I would move the variable Entered into the readdata function. Then
                        pass it as a parameter to the other functions like you do with
                        triangle.
                        [color=blue]
                        > [Several functions omitted]
                        >
                        > void triangle(int Entered,int sidea, int sideb, int sidec)
                        > {
                        >
                        > switch(Entered)
                        > {
                        > case 0 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
                        > <<" makes this a Scalene Triangle"<<endl ; break;
                        > case 1 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
                        > <<" makes this an Isosceles Triangle"<<endl ; break;
                        > case 2 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
                        > <<" makes this an Equalateral Triangle"<<endl ; break;
                        > case 3 : cout << "The dimensions " << sidea << ", "<<sideb <<", "<<sidec
                        > <<" makes this an Invalid Triangle"<<endl ; break;
                        > }
                        > }[/color]

                        "Magic numbers" in you switch statement. You should use the constants
                        defined with the Triangle enum instead. case Scalene:, case: Isoceles,
                        etc. That's what they are there though.
                        [color=blue]
                        > [Several more functions omitted][/color]

                        Sometime in the next couple days I'll post code the way I'd attack the
                        problem for comparison purposes. I don't have time at this exact
                        moment but should be able to find time in a couple days, so check
                        back. (I'll also address the file existance problem.)

                        Evan

                        Comment

                        Working...