How can I create a constant array with some calculation












0















I have code



int a[5];
for (int i = 0; i < 5; i++){
a[i] = i * i;
}


Is there a way to make this array constant so that other code can use it but not change it.










share|improve this question

























  • constexpr std::array - go from there. Don't use C-style arrays. Also; The language has const_cast so you can never be 100% certain that noone will do nasty things to your const thing (unfortunately).

    – Jesper Juhl
    Nov 12 '18 at 22:37








  • 7





    C or C++? Pick one.

    – Broman
    Nov 12 '18 at 22:37











  • Detail: C does not have constant arrays. C does has const arrays. Accepting to change an element of a const array is undefined behavior. It might work, might, not, might kill the code.

    – chux
    Nov 12 '18 at 22:49






  • 2





    Is this literally the code you have? What's wrong with const int a[5] = { 0, 1, 2, 4, 8 }; ?

    – paddy
    Nov 12 '18 at 23:03











  • Lu J., I think @paddy meant const int a[5] = { 0, 1, 4, 9, 16 };.

    – chux
    Nov 13 '18 at 2:19
















0















I have code



int a[5];
for (int i = 0; i < 5; i++){
a[i] = i * i;
}


Is there a way to make this array constant so that other code can use it but not change it.










share|improve this question

























  • constexpr std::array - go from there. Don't use C-style arrays. Also; The language has const_cast so you can never be 100% certain that noone will do nasty things to your const thing (unfortunately).

    – Jesper Juhl
    Nov 12 '18 at 22:37








  • 7





    C or C++? Pick one.

    – Broman
    Nov 12 '18 at 22:37











  • Detail: C does not have constant arrays. C does has const arrays. Accepting to change an element of a const array is undefined behavior. It might work, might, not, might kill the code.

    – chux
    Nov 12 '18 at 22:49






  • 2





    Is this literally the code you have? What's wrong with const int a[5] = { 0, 1, 2, 4, 8 }; ?

    – paddy
    Nov 12 '18 at 23:03











  • Lu J., I think @paddy meant const int a[5] = { 0, 1, 4, 9, 16 };.

    – chux
    Nov 13 '18 at 2:19














0












0








0








I have code



int a[5];
for (int i = 0; i < 5; i++){
a[i] = i * i;
}


Is there a way to make this array constant so that other code can use it but not change it.










share|improve this question
















I have code



int a[5];
for (int i = 0; i < 5; i++){
a[i] = i * i;
}


Is there a way to make this array constant so that other code can use it but not change it.







c++






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 16:44









Broman

6,257112241




6,257112241










asked Nov 12 '18 at 22:34









Lu J.Lu J.

114




114













  • constexpr std::array - go from there. Don't use C-style arrays. Also; The language has const_cast so you can never be 100% certain that noone will do nasty things to your const thing (unfortunately).

    – Jesper Juhl
    Nov 12 '18 at 22:37








  • 7





    C or C++? Pick one.

    – Broman
    Nov 12 '18 at 22:37











  • Detail: C does not have constant arrays. C does has const arrays. Accepting to change an element of a const array is undefined behavior. It might work, might, not, might kill the code.

    – chux
    Nov 12 '18 at 22:49






  • 2





    Is this literally the code you have? What's wrong with const int a[5] = { 0, 1, 2, 4, 8 }; ?

    – paddy
    Nov 12 '18 at 23:03











  • Lu J., I think @paddy meant const int a[5] = { 0, 1, 4, 9, 16 };.

    – chux
    Nov 13 '18 at 2:19



















  • constexpr std::array - go from there. Don't use C-style arrays. Also; The language has const_cast so you can never be 100% certain that noone will do nasty things to your const thing (unfortunately).

    – Jesper Juhl
    Nov 12 '18 at 22:37








  • 7





    C or C++? Pick one.

    – Broman
    Nov 12 '18 at 22:37











  • Detail: C does not have constant arrays. C does has const arrays. Accepting to change an element of a const array is undefined behavior. It might work, might, not, might kill the code.

    – chux
    Nov 12 '18 at 22:49






  • 2





    Is this literally the code you have? What's wrong with const int a[5] = { 0, 1, 2, 4, 8 }; ?

    – paddy
    Nov 12 '18 at 23:03











  • Lu J., I think @paddy meant const int a[5] = { 0, 1, 4, 9, 16 };.

    – chux
    Nov 13 '18 at 2:19

















constexpr std::array - go from there. Don't use C-style arrays. Also; The language has const_cast so you can never be 100% certain that noone will do nasty things to your const thing (unfortunately).

– Jesper Juhl
Nov 12 '18 at 22:37







constexpr std::array - go from there. Don't use C-style arrays. Also; The language has const_cast so you can never be 100% certain that noone will do nasty things to your const thing (unfortunately).

– Jesper Juhl
Nov 12 '18 at 22:37






7




7





C or C++? Pick one.

– Broman
Nov 12 '18 at 22:37





C or C++? Pick one.

– Broman
Nov 12 '18 at 22:37













Detail: C does not have constant arrays. C does has const arrays. Accepting to change an element of a const array is undefined behavior. It might work, might, not, might kill the code.

– chux
Nov 12 '18 at 22:49





Detail: C does not have constant arrays. C does has const arrays. Accepting to change an element of a const array is undefined behavior. It might work, might, not, might kill the code.

– chux
Nov 12 '18 at 22:49




2




2





Is this literally the code you have? What's wrong with const int a[5] = { 0, 1, 2, 4, 8 }; ?

– paddy
Nov 12 '18 at 23:03





Is this literally the code you have? What's wrong with const int a[5] = { 0, 1, 2, 4, 8 }; ?

– paddy
Nov 12 '18 at 23:03













Lu J., I think @paddy meant const int a[5] = { 0, 1, 4, 9, 16 };.

– chux
Nov 13 '18 at 2:19





Lu J., I think @paddy meant const int a[5] = { 0, 1, 4, 9, 16 };.

– chux
Nov 13 '18 at 2:19












2 Answers
2






active

oldest

votes


















1














Easiest way is to use constexpr function and the std::array:



constexpr std::array<int, 5> make_array() {
std::array<int, 5> a{};
for (int i = 0; i < 5; i++){
a[i] = i * i;
}
return a;
}
//...
const std::array<int, 5> a = make_array();


NB. As noted by @M.M, this code is only valid for C++17, as pre-C++17 the operator on array wasn't constexpr.






share|improve this answer


























  • Constexpr isn't really needed here. The jist of solution is the lifting of the initialization into a function.

    – NathanOliver
    Nov 12 '18 at 22:47











  • note: this code is undefined behaviour NDR prior to C++17, when operator was made constexpr

    – M.M
    Nov 12 '18 at 23:00








  • 1





    @NathanOliver it does make a difference. For example, if a is a global variable, on gcc absence of constexpr generates run-time initialization, and with constexpr the aray is statically initialized.

    – SergeyA
    Nov 12 '18 at 23:02











  • @M.M no diagnostic on godbolt for either of compilers: gcc.godbolt.org/z/I1MLLS

    – SergeyA
    Nov 12 '18 at 23:04






  • 1





    @M.M ah! Different dialect. I always use C++17 nowadays.

    – SergeyA
    Nov 12 '18 at 23:04



















0














Using modern C++ (array and an Immediately Invoked Lambda (IIL)), this can be achieved:



const auto a = () 
{
std::array< int, 5 > x;

for (int i = 0; i < 5; i++)
{
x[i] = i * i;
}

return x;
}(); // IIL


Using a lambda has benefits over a function call, that you can capture the local variables into the lambda and use them without the values passing through parameters ([&] or [=] instead of ).



Just like a function the lambda can easily be inlined into your code, so there can be no overhead.






share|improve this answer

























    Your Answer






    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: "1"
    };
    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',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53271076%2fhow-can-i-create-a-constant-array-with-some-calculation%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Easiest way is to use constexpr function and the std::array:



    constexpr std::array<int, 5> make_array() {
    std::array<int, 5> a{};
    for (int i = 0; i < 5; i++){
    a[i] = i * i;
    }
    return a;
    }
    //...
    const std::array<int, 5> a = make_array();


    NB. As noted by @M.M, this code is only valid for C++17, as pre-C++17 the operator on array wasn't constexpr.






    share|improve this answer


























    • Constexpr isn't really needed here. The jist of solution is the lifting of the initialization into a function.

      – NathanOliver
      Nov 12 '18 at 22:47











    • note: this code is undefined behaviour NDR prior to C++17, when operator was made constexpr

      – M.M
      Nov 12 '18 at 23:00








    • 1





      @NathanOliver it does make a difference. For example, if a is a global variable, on gcc absence of constexpr generates run-time initialization, and with constexpr the aray is statically initialized.

      – SergeyA
      Nov 12 '18 at 23:02











    • @M.M no diagnostic on godbolt for either of compilers: gcc.godbolt.org/z/I1MLLS

      – SergeyA
      Nov 12 '18 at 23:04






    • 1





      @M.M ah! Different dialect. I always use C++17 nowadays.

      – SergeyA
      Nov 12 '18 at 23:04
















    1














    Easiest way is to use constexpr function and the std::array:



    constexpr std::array<int, 5> make_array() {
    std::array<int, 5> a{};
    for (int i = 0; i < 5; i++){
    a[i] = i * i;
    }
    return a;
    }
    //...
    const std::array<int, 5> a = make_array();


    NB. As noted by @M.M, this code is only valid for C++17, as pre-C++17 the operator on array wasn't constexpr.






    share|improve this answer


























    • Constexpr isn't really needed here. The jist of solution is the lifting of the initialization into a function.

      – NathanOliver
      Nov 12 '18 at 22:47











    • note: this code is undefined behaviour NDR prior to C++17, when operator was made constexpr

      – M.M
      Nov 12 '18 at 23:00








    • 1





      @NathanOliver it does make a difference. For example, if a is a global variable, on gcc absence of constexpr generates run-time initialization, and with constexpr the aray is statically initialized.

      – SergeyA
      Nov 12 '18 at 23:02











    • @M.M no diagnostic on godbolt for either of compilers: gcc.godbolt.org/z/I1MLLS

      – SergeyA
      Nov 12 '18 at 23:04






    • 1





      @M.M ah! Different dialect. I always use C++17 nowadays.

      – SergeyA
      Nov 12 '18 at 23:04














    1












    1








    1







    Easiest way is to use constexpr function and the std::array:



    constexpr std::array<int, 5> make_array() {
    std::array<int, 5> a{};
    for (int i = 0; i < 5; i++){
    a[i] = i * i;
    }
    return a;
    }
    //...
    const std::array<int, 5> a = make_array();


    NB. As noted by @M.M, this code is only valid for C++17, as pre-C++17 the operator on array wasn't constexpr.






    share|improve this answer















    Easiest way is to use constexpr function and the std::array:



    constexpr std::array<int, 5> make_array() {
    std::array<int, 5> a{};
    for (int i = 0; i < 5; i++){
    a[i] = i * i;
    }
    return a;
    }
    //...
    const std::array<int, 5> a = make_array();


    NB. As noted by @M.M, this code is only valid for C++17, as pre-C++17 the operator on array wasn't constexpr.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 12 '18 at 23:05

























    answered Nov 12 '18 at 22:40









    SergeyASergeyA

    42.1k53784




    42.1k53784













    • Constexpr isn't really needed here. The jist of solution is the lifting of the initialization into a function.

      – NathanOliver
      Nov 12 '18 at 22:47











    • note: this code is undefined behaviour NDR prior to C++17, when operator was made constexpr

      – M.M
      Nov 12 '18 at 23:00








    • 1





      @NathanOliver it does make a difference. For example, if a is a global variable, on gcc absence of constexpr generates run-time initialization, and with constexpr the aray is statically initialized.

      – SergeyA
      Nov 12 '18 at 23:02











    • @M.M no diagnostic on godbolt for either of compilers: gcc.godbolt.org/z/I1MLLS

      – SergeyA
      Nov 12 '18 at 23:04






    • 1





      @M.M ah! Different dialect. I always use C++17 nowadays.

      – SergeyA
      Nov 12 '18 at 23:04



















    • Constexpr isn't really needed here. The jist of solution is the lifting of the initialization into a function.

      – NathanOliver
      Nov 12 '18 at 22:47











    • note: this code is undefined behaviour NDR prior to C++17, when operator was made constexpr

      – M.M
      Nov 12 '18 at 23:00








    • 1





      @NathanOliver it does make a difference. For example, if a is a global variable, on gcc absence of constexpr generates run-time initialization, and with constexpr the aray is statically initialized.

      – SergeyA
      Nov 12 '18 at 23:02











    • @M.M no diagnostic on godbolt for either of compilers: gcc.godbolt.org/z/I1MLLS

      – SergeyA
      Nov 12 '18 at 23:04






    • 1





      @M.M ah! Different dialect. I always use C++17 nowadays.

      – SergeyA
      Nov 12 '18 at 23:04

















    Constexpr isn't really needed here. The jist of solution is the lifting of the initialization into a function.

    – NathanOliver
    Nov 12 '18 at 22:47





    Constexpr isn't really needed here. The jist of solution is the lifting of the initialization into a function.

    – NathanOliver
    Nov 12 '18 at 22:47













    note: this code is undefined behaviour NDR prior to C++17, when operator was made constexpr

    – M.M
    Nov 12 '18 at 23:00







    note: this code is undefined behaviour NDR prior to C++17, when operator was made constexpr

    – M.M
    Nov 12 '18 at 23:00






    1




    1





    @NathanOliver it does make a difference. For example, if a is a global variable, on gcc absence of constexpr generates run-time initialization, and with constexpr the aray is statically initialized.

    – SergeyA
    Nov 12 '18 at 23:02





    @NathanOliver it does make a difference. For example, if a is a global variable, on gcc absence of constexpr generates run-time initialization, and with constexpr the aray is statically initialized.

    – SergeyA
    Nov 12 '18 at 23:02













    @M.M no diagnostic on godbolt for either of compilers: gcc.godbolt.org/z/I1MLLS

    – SergeyA
    Nov 12 '18 at 23:04





    @M.M no diagnostic on godbolt for either of compilers: gcc.godbolt.org/z/I1MLLS

    – SergeyA
    Nov 12 '18 at 23:04




    1




    1





    @M.M ah! Different dialect. I always use C++17 nowadays.

    – SergeyA
    Nov 12 '18 at 23:04





    @M.M ah! Different dialect. I always use C++17 nowadays.

    – SergeyA
    Nov 12 '18 at 23:04













    0














    Using modern C++ (array and an Immediately Invoked Lambda (IIL)), this can be achieved:



    const auto a = () 
    {
    std::array< int, 5 > x;

    for (int i = 0; i < 5; i++)
    {
    x[i] = i * i;
    }

    return x;
    }(); // IIL


    Using a lambda has benefits over a function call, that you can capture the local variables into the lambda and use them without the values passing through parameters ([&] or [=] instead of ).



    Just like a function the lambda can easily be inlined into your code, so there can be no overhead.






    share|improve this answer






























      0














      Using modern C++ (array and an Immediately Invoked Lambda (IIL)), this can be achieved:



      const auto a = () 
      {
      std::array< int, 5 > x;

      for (int i = 0; i < 5; i++)
      {
      x[i] = i * i;
      }

      return x;
      }(); // IIL


      Using a lambda has benefits over a function call, that you can capture the local variables into the lambda and use them without the values passing through parameters ([&] or [=] instead of ).



      Just like a function the lambda can easily be inlined into your code, so there can be no overhead.






      share|improve this answer




























        0












        0








        0







        Using modern C++ (array and an Immediately Invoked Lambda (IIL)), this can be achieved:



        const auto a = () 
        {
        std::array< int, 5 > x;

        for (int i = 0; i < 5; i++)
        {
        x[i] = i * i;
        }

        return x;
        }(); // IIL


        Using a lambda has benefits over a function call, that you can capture the local variables into the lambda and use them without the values passing through parameters ([&] or [=] instead of ).



        Just like a function the lambda can easily be inlined into your code, so there can be no overhead.






        share|improve this answer















        Using modern C++ (array and an Immediately Invoked Lambda (IIL)), this can be achieved:



        const auto a = () 
        {
        std::array< int, 5 > x;

        for (int i = 0; i < 5; i++)
        {
        x[i] = i * i;
        }

        return x;
        }(); // IIL


        Using a lambda has benefits over a function call, that you can capture the local variables into the lambda and use them without the values passing through parameters ([&] or [=] instead of ).



        Just like a function the lambda can easily be inlined into your code, so there can be no overhead.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 14 '18 at 12:42

























        answered Nov 12 '18 at 23:13









        Robert AndrzejukRobert Andrzejuk

        2,71521324




        2,71521324






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53271076%2fhow-can-i-create-a-constant-array-with-some-calculation%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Full-time equivalent

            さくらももこ

            13 indicted, 8 arrested in Calif. drug cartel investigation