Passing an array created in function to other functions

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty margin-bottom:0;







up vote
3
down vote

favorite
1












I'm beginning my programming adventure in C++. I want to write a small program, which has to create an array in function create (size has to be defined in create function) and transfer them to function display which will print entered values.



#include <iostream>

using namespace std;

int *create(int & n);
void display(int * arr, int n);

int main()

int n;
int * arr = create(n);
display(arr, n);


delete arr;

return 0;


int *create(int & n)
cout << "How many elements? ";
cin >> n;
int * arr = new int[n];
int element;
for(int i = 0; i < n; i++)
cout << endl << "Enter " << i << " array element: ";
cin >> element;
arr[i] = element;


return arr;


void display(int * arr, int n)
for(int i = 0; i < n; i++)
cout << endl << i << " element: " << arr[i];




I'm looking for every criticism, optimization suggest and everything which will help me be a better programmer and not to learn bad habits from the beginning.







share|improve this question



























    up vote
    3
    down vote

    favorite
    1












    I'm beginning my programming adventure in C++. I want to write a small program, which has to create an array in function create (size has to be defined in create function) and transfer them to function display which will print entered values.



    #include <iostream>

    using namespace std;

    int *create(int & n);
    void display(int * arr, int n);

    int main()

    int n;
    int * arr = create(n);
    display(arr, n);


    delete arr;

    return 0;


    int *create(int & n)
    cout << "How many elements? ";
    cin >> n;
    int * arr = new int[n];
    int element;
    for(int i = 0; i < n; i++)
    cout << endl << "Enter " << i << " array element: ";
    cin >> element;
    arr[i] = element;


    return arr;


    void display(int * arr, int n)
    for(int i = 0; i < n; i++)
    cout << endl << i << " element: " << arr[i];




    I'm looking for every criticism, optimization suggest and everything which will help me be a better programmer and not to learn bad habits from the beginning.







    share|improve this question























      up vote
      3
      down vote

      favorite
      1









      up vote
      3
      down vote

      favorite
      1






      1





      I'm beginning my programming adventure in C++. I want to write a small program, which has to create an array in function create (size has to be defined in create function) and transfer them to function display which will print entered values.



      #include <iostream>

      using namespace std;

      int *create(int & n);
      void display(int * arr, int n);

      int main()

      int n;
      int * arr = create(n);
      display(arr, n);


      delete arr;

      return 0;


      int *create(int & n)
      cout << "How many elements? ";
      cin >> n;
      int * arr = new int[n];
      int element;
      for(int i = 0; i < n; i++)
      cout << endl << "Enter " << i << " array element: ";
      cin >> element;
      arr[i] = element;


      return arr;


      void display(int * arr, int n)
      for(int i = 0; i < n; i++)
      cout << endl << i << " element: " << arr[i];




      I'm looking for every criticism, optimization suggest and everything which will help me be a better programmer and not to learn bad habits from the beginning.







      share|improve this question













      I'm beginning my programming adventure in C++. I want to write a small program, which has to create an array in function create (size has to be defined in create function) and transfer them to function display which will print entered values.



      #include <iostream>

      using namespace std;

      int *create(int & n);
      void display(int * arr, int n);

      int main()

      int n;
      int * arr = create(n);
      display(arr, n);


      delete arr;

      return 0;


      int *create(int & n)
      cout << "How many elements? ";
      cin >> n;
      int * arr = new int[n];
      int element;
      for(int i = 0; i < n; i++)
      cout << endl << "Enter " << i << " array element: ";
      cin >> element;
      arr[i] = element;


      return arr;


      void display(int * arr, int n)
      for(int i = 0; i < n; i++)
      cout << endl << i << " element: " << arr[i];




      I'm looking for every criticism, optimization suggest and everything which will help me be a better programmer and not to learn bad habits from the beginning.









      share|improve this question












      share|improve this question




      share|improve this question








      edited Mar 25 at 17:17









      Jamal♦

      30.1k11114225




      30.1k11114225









      asked Mar 25 at 16:30









      szeejdi

      183




      183




















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          4
          down vote



          accepted










          First, the usual criticisms:



          • Don't use using namespace std;

          • Don't use raw new and delete

          • Include the headers your code uses (e.g. <iostream>)

          • Prefer prefix ++i over postfix i++ as a general habit

          • Prefer to omit the implied return 0; from main (unless you're trying to emphasize that the return value is different via different codepaths, which doesn't apply in this case)

          Then, the point specific to your API design:



          • Your function create has two outputs: the pointer to a new array and the size of the new array, n. The former is returned as the return value; the latter is passed in by reference (the out-parameter pattern). Instead of returning these two pieces of information by two different routes, you should unify them: Either pass in two out-parameters (yuck!) or pass out two values by return.

          Taking the latter approach (two values by return) and applying all our rules except "no raw new and delete", we end up with this:



          #include <iostream>
          #include <utility>

          std::pair<int *, int> create()
          int n;
          std::cout << "How many elements? ";
          std::cin >> n;
          int *arr = new int[n];
          for (int i = 0; i < n; ++i)
          int element;
          std::cout << std::endl << "Enter " << i << " array element: ";
          std::cin >> element;
          arr[i] = element;

          return arr, n;


          void display(int *arr, int n)
          for (int i = 0; i < n; ++i)
          std::cout << std::endl << i << " element: " << arr[i];



          int main()
          auto [arr, n] = create(n);
          display(arr, n);
          delete arr;



          The JavaScript-looking [arr, n] is C++17 syntax, but don't worry, we're about to get rid of it in our next refactor.



          Applying "no raw new and delete" allows us to simplify much further:



          #include <iostream>
          #include <vector>

          std::vector<int> create()
          int n;
          std::cout << "How many elements? ";
          std::cin >> n;
          std::vector<int> result;
          for (int i = 0; i < n; ++i)
          int element;
          std::cout << std::endl << "Enter " << i << " array element: ";
          std::cin >> element;
          result.push_back(element);

          return result;


          void display(const std::vector<int>& vec)
          for (int i = 0; i < int(vec.size()); ++i)
          std::cout << std::endl << i << " element: " << vec[i];



          int main()
          auto vec = create(n);
          display(vec);



          The last thing I'd consider doing is eliminating mutation from the code. You've got these variables int n and int element that aren't initialized, and then you use std::cin >> ... to mutate their values. It might be more straightforward to write an "int-getting function" and use it consistently. Plus, this gives us a place to hang the missing std::flush:



          #include <iostream>
          #include <vector>

          template<class T>
          T input(const char *prompt)
          T result;
          // Print out everything in `prompt` (C++17 syntax)
          std::cout << prompt << " " << std::flush;
          std::cin >> result; // Should we add some error-checking?
          // What if the user types "hello world" here?
          return result;


          std::vector<int> create()
          std::vector<int> result;
          int n = input<int>("How many elements?");
          for (int i = 0; i < n; ++i)
          result.push_back(input<int>("Enter the next array element:"));

          return result;


          void display(const std::vector<int>& vec)
          for (int i = 0; i < int(vec.size()); ++i)
          std::cout << std::endl << i << " element: " << vec[i];



          int main()
          display(create(n));



          Notice that I changed your prompt from "Enter the 42 array element:" to simply "Enter the next array element:". This was because I didn't want to bother explaining how to write a variadic-template version of input that would accept input<int>("Enter the ", i, " array element:"). It's possible — even trivial, in C++17 where we can write (std::cout << ... << prompt_pieces) << " " << std::flush — but I want to keep the simple code simple.



          Now we've localized all the icky "state mutation" into the innards of input<int>; we don't have to think about mutation while we're reading create.






          share|improve this answer



















          • 1




            I guess I’m not the only one abusing templates :) also, did you want to return T from input?
            – Incomputable
            Mar 25 at 17:49











          • Good call! Fixed. (And yeah, I had it as a non-template at first, but then figured the template version wouldn't be too complicated. As indicated, I resisted the urge to make it take anything more complicated than const char *.)
            – Quuxplusone
            Mar 25 at 17:55






          • 1




            @Quuxplusone Nice work :) Now i'll study your improvements for my code, it really looks so much better. Thank you so much! :)
            – szeejdi
            Mar 25 at 18:00











          • You can emphasise the non-mutating nature in create() by writing const int n = input... (though I'd recommend a std::size_t for the size) - is it also worth mentioning std::vector::reserve() once the size is known?
            – Toby Speight
            Mar 27 at 7:37










          Your Answer




          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: false,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );








           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f190445%2fpassing-an-array-created-in-function-to-other-functions%23new-answer', 'question_page');

          );

          Post as a guest






























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          4
          down vote



          accepted










          First, the usual criticisms:



          • Don't use using namespace std;

          • Don't use raw new and delete

          • Include the headers your code uses (e.g. <iostream>)

          • Prefer prefix ++i over postfix i++ as a general habit

          • Prefer to omit the implied return 0; from main (unless you're trying to emphasize that the return value is different via different codepaths, which doesn't apply in this case)

          Then, the point specific to your API design:



          • Your function create has two outputs: the pointer to a new array and the size of the new array, n. The former is returned as the return value; the latter is passed in by reference (the out-parameter pattern). Instead of returning these two pieces of information by two different routes, you should unify them: Either pass in two out-parameters (yuck!) or pass out two values by return.

          Taking the latter approach (two values by return) and applying all our rules except "no raw new and delete", we end up with this:



          #include <iostream>
          #include <utility>

          std::pair<int *, int> create()
          int n;
          std::cout << "How many elements? ";
          std::cin >> n;
          int *arr = new int[n];
          for (int i = 0; i < n; ++i)
          int element;
          std::cout << std::endl << "Enter " << i << " array element: ";
          std::cin >> element;
          arr[i] = element;

          return arr, n;


          void display(int *arr, int n)
          for (int i = 0; i < n; ++i)
          std::cout << std::endl << i << " element: " << arr[i];



          int main()
          auto [arr, n] = create(n);
          display(arr, n);
          delete arr;



          The JavaScript-looking [arr, n] is C++17 syntax, but don't worry, we're about to get rid of it in our next refactor.



          Applying "no raw new and delete" allows us to simplify much further:



          #include <iostream>
          #include <vector>

          std::vector<int> create()
          int n;
          std::cout << "How many elements? ";
          std::cin >> n;
          std::vector<int> result;
          for (int i = 0; i < n; ++i)
          int element;
          std::cout << std::endl << "Enter " << i << " array element: ";
          std::cin >> element;
          result.push_back(element);

          return result;


          void display(const std::vector<int>& vec)
          for (int i = 0; i < int(vec.size()); ++i)
          std::cout << std::endl << i << " element: " << vec[i];



          int main()
          auto vec = create(n);
          display(vec);



          The last thing I'd consider doing is eliminating mutation from the code. You've got these variables int n and int element that aren't initialized, and then you use std::cin >> ... to mutate their values. It might be more straightforward to write an "int-getting function" and use it consistently. Plus, this gives us a place to hang the missing std::flush:



          #include <iostream>
          #include <vector>

          template<class T>
          T input(const char *prompt)
          T result;
          // Print out everything in `prompt` (C++17 syntax)
          std::cout << prompt << " " << std::flush;
          std::cin >> result; // Should we add some error-checking?
          // What if the user types "hello world" here?
          return result;


          std::vector<int> create()
          std::vector<int> result;
          int n = input<int>("How many elements?");
          for (int i = 0; i < n; ++i)
          result.push_back(input<int>("Enter the next array element:"));

          return result;


          void display(const std::vector<int>& vec)
          for (int i = 0; i < int(vec.size()); ++i)
          std::cout << std::endl << i << " element: " << vec[i];



          int main()
          display(create(n));



          Notice that I changed your prompt from "Enter the 42 array element:" to simply "Enter the next array element:". This was because I didn't want to bother explaining how to write a variadic-template version of input that would accept input<int>("Enter the ", i, " array element:"). It's possible — even trivial, in C++17 where we can write (std::cout << ... << prompt_pieces) << " " << std::flush — but I want to keep the simple code simple.



          Now we've localized all the icky "state mutation" into the innards of input<int>; we don't have to think about mutation while we're reading create.






          share|improve this answer



















          • 1




            I guess I’m not the only one abusing templates :) also, did you want to return T from input?
            – Incomputable
            Mar 25 at 17:49











          • Good call! Fixed. (And yeah, I had it as a non-template at first, but then figured the template version wouldn't be too complicated. As indicated, I resisted the urge to make it take anything more complicated than const char *.)
            – Quuxplusone
            Mar 25 at 17:55






          • 1




            @Quuxplusone Nice work :) Now i'll study your improvements for my code, it really looks so much better. Thank you so much! :)
            – szeejdi
            Mar 25 at 18:00











          • You can emphasise the non-mutating nature in create() by writing const int n = input... (though I'd recommend a std::size_t for the size) - is it also worth mentioning std::vector::reserve() once the size is known?
            – Toby Speight
            Mar 27 at 7:37














          up vote
          4
          down vote



          accepted










          First, the usual criticisms:



          • Don't use using namespace std;

          • Don't use raw new and delete

          • Include the headers your code uses (e.g. <iostream>)

          • Prefer prefix ++i over postfix i++ as a general habit

          • Prefer to omit the implied return 0; from main (unless you're trying to emphasize that the return value is different via different codepaths, which doesn't apply in this case)

          Then, the point specific to your API design:



          • Your function create has two outputs: the pointer to a new array and the size of the new array, n. The former is returned as the return value; the latter is passed in by reference (the out-parameter pattern). Instead of returning these two pieces of information by two different routes, you should unify them: Either pass in two out-parameters (yuck!) or pass out two values by return.

          Taking the latter approach (two values by return) and applying all our rules except "no raw new and delete", we end up with this:



          #include <iostream>
          #include <utility>

          std::pair<int *, int> create()
          int n;
          std::cout << "How many elements? ";
          std::cin >> n;
          int *arr = new int[n];
          for (int i = 0; i < n; ++i)
          int element;
          std::cout << std::endl << "Enter " << i << " array element: ";
          std::cin >> element;
          arr[i] = element;

          return arr, n;


          void display(int *arr, int n)
          for (int i = 0; i < n; ++i)
          std::cout << std::endl << i << " element: " << arr[i];



          int main()
          auto [arr, n] = create(n);
          display(arr, n);
          delete arr;



          The JavaScript-looking [arr, n] is C++17 syntax, but don't worry, we're about to get rid of it in our next refactor.



          Applying "no raw new and delete" allows us to simplify much further:



          #include <iostream>
          #include <vector>

          std::vector<int> create()
          int n;
          std::cout << "How many elements? ";
          std::cin >> n;
          std::vector<int> result;
          for (int i = 0; i < n; ++i)
          int element;
          std::cout << std::endl << "Enter " << i << " array element: ";
          std::cin >> element;
          result.push_back(element);

          return result;


          void display(const std::vector<int>& vec)
          for (int i = 0; i < int(vec.size()); ++i)
          std::cout << std::endl << i << " element: " << vec[i];



          int main()
          auto vec = create(n);
          display(vec);



          The last thing I'd consider doing is eliminating mutation from the code. You've got these variables int n and int element that aren't initialized, and then you use std::cin >> ... to mutate their values. It might be more straightforward to write an "int-getting function" and use it consistently. Plus, this gives us a place to hang the missing std::flush:



          #include <iostream>
          #include <vector>

          template<class T>
          T input(const char *prompt)
          T result;
          // Print out everything in `prompt` (C++17 syntax)
          std::cout << prompt << " " << std::flush;
          std::cin >> result; // Should we add some error-checking?
          // What if the user types "hello world" here?
          return result;


          std::vector<int> create()
          std::vector<int> result;
          int n = input<int>("How many elements?");
          for (int i = 0; i < n; ++i)
          result.push_back(input<int>("Enter the next array element:"));

          return result;


          void display(const std::vector<int>& vec)
          for (int i = 0; i < int(vec.size()); ++i)
          std::cout << std::endl << i << " element: " << vec[i];



          int main()
          display(create(n));



          Notice that I changed your prompt from "Enter the 42 array element:" to simply "Enter the next array element:". This was because I didn't want to bother explaining how to write a variadic-template version of input that would accept input<int>("Enter the ", i, " array element:"). It's possible — even trivial, in C++17 where we can write (std::cout << ... << prompt_pieces) << " " << std::flush — but I want to keep the simple code simple.



          Now we've localized all the icky "state mutation" into the innards of input<int>; we don't have to think about mutation while we're reading create.






          share|improve this answer



















          • 1




            I guess I’m not the only one abusing templates :) also, did you want to return T from input?
            – Incomputable
            Mar 25 at 17:49











          • Good call! Fixed. (And yeah, I had it as a non-template at first, but then figured the template version wouldn't be too complicated. As indicated, I resisted the urge to make it take anything more complicated than const char *.)
            – Quuxplusone
            Mar 25 at 17:55






          • 1




            @Quuxplusone Nice work :) Now i'll study your improvements for my code, it really looks so much better. Thank you so much! :)
            – szeejdi
            Mar 25 at 18:00











          • You can emphasise the non-mutating nature in create() by writing const int n = input... (though I'd recommend a std::size_t for the size) - is it also worth mentioning std::vector::reserve() once the size is known?
            – Toby Speight
            Mar 27 at 7:37












          up vote
          4
          down vote



          accepted







          up vote
          4
          down vote



          accepted






          First, the usual criticisms:



          • Don't use using namespace std;

          • Don't use raw new and delete

          • Include the headers your code uses (e.g. <iostream>)

          • Prefer prefix ++i over postfix i++ as a general habit

          • Prefer to omit the implied return 0; from main (unless you're trying to emphasize that the return value is different via different codepaths, which doesn't apply in this case)

          Then, the point specific to your API design:



          • Your function create has two outputs: the pointer to a new array and the size of the new array, n. The former is returned as the return value; the latter is passed in by reference (the out-parameter pattern). Instead of returning these two pieces of information by two different routes, you should unify them: Either pass in two out-parameters (yuck!) or pass out two values by return.

          Taking the latter approach (two values by return) and applying all our rules except "no raw new and delete", we end up with this:



          #include <iostream>
          #include <utility>

          std::pair<int *, int> create()
          int n;
          std::cout << "How many elements? ";
          std::cin >> n;
          int *arr = new int[n];
          for (int i = 0; i < n; ++i)
          int element;
          std::cout << std::endl << "Enter " << i << " array element: ";
          std::cin >> element;
          arr[i] = element;

          return arr, n;


          void display(int *arr, int n)
          for (int i = 0; i < n; ++i)
          std::cout << std::endl << i << " element: " << arr[i];



          int main()
          auto [arr, n] = create(n);
          display(arr, n);
          delete arr;



          The JavaScript-looking [arr, n] is C++17 syntax, but don't worry, we're about to get rid of it in our next refactor.



          Applying "no raw new and delete" allows us to simplify much further:



          #include <iostream>
          #include <vector>

          std::vector<int> create()
          int n;
          std::cout << "How many elements? ";
          std::cin >> n;
          std::vector<int> result;
          for (int i = 0; i < n; ++i)
          int element;
          std::cout << std::endl << "Enter " << i << " array element: ";
          std::cin >> element;
          result.push_back(element);

          return result;


          void display(const std::vector<int>& vec)
          for (int i = 0; i < int(vec.size()); ++i)
          std::cout << std::endl << i << " element: " << vec[i];



          int main()
          auto vec = create(n);
          display(vec);



          The last thing I'd consider doing is eliminating mutation from the code. You've got these variables int n and int element that aren't initialized, and then you use std::cin >> ... to mutate their values. It might be more straightforward to write an "int-getting function" and use it consistently. Plus, this gives us a place to hang the missing std::flush:



          #include <iostream>
          #include <vector>

          template<class T>
          T input(const char *prompt)
          T result;
          // Print out everything in `prompt` (C++17 syntax)
          std::cout << prompt << " " << std::flush;
          std::cin >> result; // Should we add some error-checking?
          // What if the user types "hello world" here?
          return result;


          std::vector<int> create()
          std::vector<int> result;
          int n = input<int>("How many elements?");
          for (int i = 0; i < n; ++i)
          result.push_back(input<int>("Enter the next array element:"));

          return result;


          void display(const std::vector<int>& vec)
          for (int i = 0; i < int(vec.size()); ++i)
          std::cout << std::endl << i << " element: " << vec[i];



          int main()
          display(create(n));



          Notice that I changed your prompt from "Enter the 42 array element:" to simply "Enter the next array element:". This was because I didn't want to bother explaining how to write a variadic-template version of input that would accept input<int>("Enter the ", i, " array element:"). It's possible — even trivial, in C++17 where we can write (std::cout << ... << prompt_pieces) << " " << std::flush — but I want to keep the simple code simple.



          Now we've localized all the icky "state mutation" into the innards of input<int>; we don't have to think about mutation while we're reading create.






          share|improve this answer















          First, the usual criticisms:



          • Don't use using namespace std;

          • Don't use raw new and delete

          • Include the headers your code uses (e.g. <iostream>)

          • Prefer prefix ++i over postfix i++ as a general habit

          • Prefer to omit the implied return 0; from main (unless you're trying to emphasize that the return value is different via different codepaths, which doesn't apply in this case)

          Then, the point specific to your API design:



          • Your function create has two outputs: the pointer to a new array and the size of the new array, n. The former is returned as the return value; the latter is passed in by reference (the out-parameter pattern). Instead of returning these two pieces of information by two different routes, you should unify them: Either pass in two out-parameters (yuck!) or pass out two values by return.

          Taking the latter approach (two values by return) and applying all our rules except "no raw new and delete", we end up with this:



          #include <iostream>
          #include <utility>

          std::pair<int *, int> create()
          int n;
          std::cout << "How many elements? ";
          std::cin >> n;
          int *arr = new int[n];
          for (int i = 0; i < n; ++i)
          int element;
          std::cout << std::endl << "Enter " << i << " array element: ";
          std::cin >> element;
          arr[i] = element;

          return arr, n;


          void display(int *arr, int n)
          for (int i = 0; i < n; ++i)
          std::cout << std::endl << i << " element: " << arr[i];



          int main()
          auto [arr, n] = create(n);
          display(arr, n);
          delete arr;



          The JavaScript-looking [arr, n] is C++17 syntax, but don't worry, we're about to get rid of it in our next refactor.



          Applying "no raw new and delete" allows us to simplify much further:



          #include <iostream>
          #include <vector>

          std::vector<int> create()
          int n;
          std::cout << "How many elements? ";
          std::cin >> n;
          std::vector<int> result;
          for (int i = 0; i < n; ++i)
          int element;
          std::cout << std::endl << "Enter " << i << " array element: ";
          std::cin >> element;
          result.push_back(element);

          return result;


          void display(const std::vector<int>& vec)
          for (int i = 0; i < int(vec.size()); ++i)
          std::cout << std::endl << i << " element: " << vec[i];



          int main()
          auto vec = create(n);
          display(vec);



          The last thing I'd consider doing is eliminating mutation from the code. You've got these variables int n and int element that aren't initialized, and then you use std::cin >> ... to mutate their values. It might be more straightforward to write an "int-getting function" and use it consistently. Plus, this gives us a place to hang the missing std::flush:



          #include <iostream>
          #include <vector>

          template<class T>
          T input(const char *prompt)
          T result;
          // Print out everything in `prompt` (C++17 syntax)
          std::cout << prompt << " " << std::flush;
          std::cin >> result; // Should we add some error-checking?
          // What if the user types "hello world" here?
          return result;


          std::vector<int> create()
          std::vector<int> result;
          int n = input<int>("How many elements?");
          for (int i = 0; i < n; ++i)
          result.push_back(input<int>("Enter the next array element:"));

          return result;


          void display(const std::vector<int>& vec)
          for (int i = 0; i < int(vec.size()); ++i)
          std::cout << std::endl << i << " element: " << vec[i];



          int main()
          display(create(n));



          Notice that I changed your prompt from "Enter the 42 array element:" to simply "Enter the next array element:". This was because I didn't want to bother explaining how to write a variadic-template version of input that would accept input<int>("Enter the ", i, " array element:"). It's possible — even trivial, in C++17 where we can write (std::cout << ... << prompt_pieces) << " " << std::flush — but I want to keep the simple code simple.



          Now we've localized all the icky "state mutation" into the innards of input<int>; we don't have to think about mutation while we're reading create.







          share|improve this answer















          share|improve this answer



          share|improve this answer








          edited Mar 25 at 17:55


























          answered Mar 25 at 17:13









          Quuxplusone

          9,82511451




          9,82511451







          • 1




            I guess I’m not the only one abusing templates :) also, did you want to return T from input?
            – Incomputable
            Mar 25 at 17:49











          • Good call! Fixed. (And yeah, I had it as a non-template at first, but then figured the template version wouldn't be too complicated. As indicated, I resisted the urge to make it take anything more complicated than const char *.)
            – Quuxplusone
            Mar 25 at 17:55






          • 1




            @Quuxplusone Nice work :) Now i'll study your improvements for my code, it really looks so much better. Thank you so much! :)
            – szeejdi
            Mar 25 at 18:00











          • You can emphasise the non-mutating nature in create() by writing const int n = input... (though I'd recommend a std::size_t for the size) - is it also worth mentioning std::vector::reserve() once the size is known?
            – Toby Speight
            Mar 27 at 7:37












          • 1




            I guess I’m not the only one abusing templates :) also, did you want to return T from input?
            – Incomputable
            Mar 25 at 17:49











          • Good call! Fixed. (And yeah, I had it as a non-template at first, but then figured the template version wouldn't be too complicated. As indicated, I resisted the urge to make it take anything more complicated than const char *.)
            – Quuxplusone
            Mar 25 at 17:55






          • 1




            @Quuxplusone Nice work :) Now i'll study your improvements for my code, it really looks so much better. Thank you so much! :)
            – szeejdi
            Mar 25 at 18:00











          • You can emphasise the non-mutating nature in create() by writing const int n = input... (though I'd recommend a std::size_t for the size) - is it also worth mentioning std::vector::reserve() once the size is known?
            – Toby Speight
            Mar 27 at 7:37







          1




          1




          I guess I’m not the only one abusing templates :) also, did you want to return T from input?
          – Incomputable
          Mar 25 at 17:49





          I guess I’m not the only one abusing templates :) also, did you want to return T from input?
          – Incomputable
          Mar 25 at 17:49













          Good call! Fixed. (And yeah, I had it as a non-template at first, but then figured the template version wouldn't be too complicated. As indicated, I resisted the urge to make it take anything more complicated than const char *.)
          – Quuxplusone
          Mar 25 at 17:55




          Good call! Fixed. (And yeah, I had it as a non-template at first, but then figured the template version wouldn't be too complicated. As indicated, I resisted the urge to make it take anything more complicated than const char *.)
          – Quuxplusone
          Mar 25 at 17:55




          1




          1




          @Quuxplusone Nice work :) Now i'll study your improvements for my code, it really looks so much better. Thank you so much! :)
          – szeejdi
          Mar 25 at 18:00





          @Quuxplusone Nice work :) Now i'll study your improvements for my code, it really looks so much better. Thank you so much! :)
          – szeejdi
          Mar 25 at 18:00













          You can emphasise the non-mutating nature in create() by writing const int n = input... (though I'd recommend a std::size_t for the size) - is it also worth mentioning std::vector::reserve() once the size is known?
          – Toby Speight
          Mar 27 at 7:37




          You can emphasise the non-mutating nature in create() by writing const int n = input... (though I'd recommend a std::size_t for the size) - is it also worth mentioning std::vector::reserve() once the size is known?
          – Toby Speight
          Mar 27 at 7:37












           

          draft saved


          draft discarded


























           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f190445%2fpassing-an-array-created-in-function-to-other-functions%23new-answer', 'question_page');

          );

          Post as a guest













































































          Popular posts from this blog

          Python Lists

          Aion

          JavaScript Array Iteration Methods