Why is const int fine for char brace init?Why can't I convert 'char**' to a 'const char* const*' in C?Why use static_cast<int>(x) instead of (int)x?How to convert a std::string to const char* or char*?What is the difference between char * const and const char *?What is the difference between const int*, const int * const, and int const *?assigning char to int reference and const int reference in C++Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviationsInitialize vector <char> with int valuesCannot initialize a vector of const char*/string array with an initializer-list on declaration

Can i say "I will encrypt something" if i hash something?

How to create a list of dictionaries from a dictionary with lists of different lengths

Is there any detail about ambulances in Star Wars?

Does the word “uzi” need to be capitalized?

Why didn't Thor use the All powerful spear instead of Stormbreaker?

Has any object launched from Earth gone into the Sun?

How does Vivi differ from other Black Mages?

Why are some Mac apps not available on AppStore?

Gas pipes - why does gas burn "outwards?"

Can the Warforged Integrated Weapon Trait be Disarmed?

Can board a plane to Cameroon without a Cameroonian visa?

How much power do LED smart bulb wireless control systems consume when the light is turned off?

What is negative current?

Guitar beginner - What does this card show?

What is this dollar sign ($) icon in my Menu Bar?

Why is the the worst case for this function O(n^2)?

How would two worlds first establish an exchange rate between their currencies

Number of aircraft to operate in an airline company

What are the advantages and disadvantages of Preprepints.org compared with arXiv?

Character theory and Quantum Chemistry

Procedure for traffic not in sight

Could the government trigger by-elections to regain a majority?

Was Robin Hood's point of view ethically sound?

How would a village use its river that it shares with another village downstream?



Why is const int fine for char brace init?


Why can't I convert 'char**' to a 'const char* const*' in C?Why use static_cast<int>(x) instead of (int)x?How to convert a std::string to const char* or char*?What is the difference between char * const and const char *?What is the difference between const int*, const int * const, and int const *?assigning char to int reference and const int reference in C++Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviationsInitialize vector <char> with int valuesCannot initialize a vector of const char*/string array with an initializer-list on declaration






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








11















I thought brace initialization doesn't allow narrowing. But why is int const allowed for char brace initialization?



int value1 = 12;
char c1value1; // error! no narrowing

const int value2 = 12;
char c2value2; // why is this fine?


See it on Godbolt.










share|improve this question
































    11















    I thought brace initialization doesn't allow narrowing. But why is int const allowed for char brace initialization?



    int value1 = 12;
    char c1value1; // error! no narrowing

    const int value2 = 12;
    char c2value2; // why is this fine?


    See it on Godbolt.










    share|improve this question




























      11












      11








      11








      I thought brace initialization doesn't allow narrowing. But why is int const allowed for char brace initialization?



      int value1 = 12;
      char c1value1; // error! no narrowing

      const int value2 = 12;
      char c2value2; // why is this fine?


      See it on Godbolt.










      share|improve this question
















      I thought brace initialization doesn't allow narrowing. But why is int const allowed for char brace initialization?



      int value1 = 12;
      char c1value1; // error! no narrowing

      const int value2 = 12;
      char c2value2; // why is this fine?


      See it on Godbolt.







      c++ c++11 const narrowing






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 8 hours ago









      Boann

      39k13 gold badges93 silver badges123 bronze badges




      39k13 gold badges93 silver badges123 bronze badges










      asked 9 hours ago









      BK C.BK C.

      1831 gold badge2 silver badges9 bronze badges




      1831 gold badge2 silver badges9 bronze badges

























          2 Answers
          2






          active

          oldest

          votes


















          13

















          const int value2 = 12;



          value2 is a compile-time constant. The compiler can easily (and has to) prove that the value is 12 which happens to be within the range of values representable by char.




          int value1 = 12;



          value1 is not a compile-time constant. The value of the variable could change at runtime.



          The exact wording of the standard rule (quoting latest draft, emphasis added):




          [dcl.init.list]/7



          A narrowing conversion is an implicit conversion



          • from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.






          share|improve this answer


































            -4
















            #include <iostream>
            #include <vector>


            int main()
            int value1 = 12;
            char c1value1; // error! no narrowing

            const int value2 = 12;
            char c2value2; // why is this fine?



            Warning thrown by your program.



            test.cpp: In function ‘int main()’:
            test.cpp:7:19: warning: narrowing conversion of ‘value1’ from ‘int’ to ‘char’ inside [-Wnarrowing]
            char c1value1; // error! no narrowing
            ^


            Its happens because const int 12 is optimized by compiler to literal 12. While int value1 is not compile time constant(although known at compile time in this case).



            Note: For c++11 or greater, contrexpr is recommended.






            share|improve this answer






















            • 3





              This reasoning is wrong. Compiler optimizations have not happened at the point where the compiler decides whether the code is valid or not. And you get the same error even without any optimizations. Further, value1 is definitely not opaque to compiler optimizations. It's just that value2 is a constant expression while value1 is not.

              – Max Langhof
              9 hours ago












            • Corrected, @MaxLanghof

              – v78
              8 hours ago













            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/4.0/"u003ecc by-sa 4.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%2f57855180%2fwhy-is-const-int-fine-for-char-brace-init%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









            13

















            const int value2 = 12;



            value2 is a compile-time constant. The compiler can easily (and has to) prove that the value is 12 which happens to be within the range of values representable by char.




            int value1 = 12;



            value1 is not a compile-time constant. The value of the variable could change at runtime.



            The exact wording of the standard rule (quoting latest draft, emphasis added):




            [dcl.init.list]/7



            A narrowing conversion is an implicit conversion



            • from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.






            share|improve this answer































              13

















              const int value2 = 12;



              value2 is a compile-time constant. The compiler can easily (and has to) prove that the value is 12 which happens to be within the range of values representable by char.




              int value1 = 12;



              value1 is not a compile-time constant. The value of the variable could change at runtime.



              The exact wording of the standard rule (quoting latest draft, emphasis added):




              [dcl.init.list]/7



              A narrowing conversion is an implicit conversion



              • from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.






              share|improve this answer





























                13














                13










                13










                const int value2 = 12;



                value2 is a compile-time constant. The compiler can easily (and has to) prove that the value is 12 which happens to be within the range of values representable by char.




                int value1 = 12;



                value1 is not a compile-time constant. The value of the variable could change at runtime.



                The exact wording of the standard rule (quoting latest draft, emphasis added):




                [dcl.init.list]/7



                A narrowing conversion is an implicit conversion



                • from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.






                share|improve this answer
















                const int value2 = 12;



                value2 is a compile-time constant. The compiler can easily (and has to) prove that the value is 12 which happens to be within the range of values representable by char.




                int value1 = 12;



                value1 is not a compile-time constant. The value of the variable could change at runtime.



                The exact wording of the standard rule (quoting latest draft, emphasis added):




                [dcl.init.list]/7



                A narrowing conversion is an implicit conversion



                • from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited 8 hours ago









                Max Langhof

                15.9k3 gold badges26 silver badges48 bronze badges




                15.9k3 gold badges26 silver badges48 bronze badges










                answered 9 hours ago









                eerorikaeerorika

                105k6 gold badges86 silver badges162 bronze badges




                105k6 gold badges86 silver badges162 bronze badges


























                    -4
















                    #include <iostream>
                    #include <vector>


                    int main()
                    int value1 = 12;
                    char c1value1; // error! no narrowing

                    const int value2 = 12;
                    char c2value2; // why is this fine?



                    Warning thrown by your program.



                    test.cpp: In function ‘int main()’:
                    test.cpp:7:19: warning: narrowing conversion of ‘value1’ from ‘int’ to ‘char’ inside [-Wnarrowing]
                    char c1value1; // error! no narrowing
                    ^


                    Its happens because const int 12 is optimized by compiler to literal 12. While int value1 is not compile time constant(although known at compile time in this case).



                    Note: For c++11 or greater, contrexpr is recommended.






                    share|improve this answer






















                    • 3





                      This reasoning is wrong. Compiler optimizations have not happened at the point where the compiler decides whether the code is valid or not. And you get the same error even without any optimizations. Further, value1 is definitely not opaque to compiler optimizations. It's just that value2 is a constant expression while value1 is not.

                      – Max Langhof
                      9 hours ago












                    • Corrected, @MaxLanghof

                      – v78
                      8 hours ago















                    -4
















                    #include <iostream>
                    #include <vector>


                    int main()
                    int value1 = 12;
                    char c1value1; // error! no narrowing

                    const int value2 = 12;
                    char c2value2; // why is this fine?



                    Warning thrown by your program.



                    test.cpp: In function ‘int main()’:
                    test.cpp:7:19: warning: narrowing conversion of ‘value1’ from ‘int’ to ‘char’ inside [-Wnarrowing]
                    char c1value1; // error! no narrowing
                    ^


                    Its happens because const int 12 is optimized by compiler to literal 12. While int value1 is not compile time constant(although known at compile time in this case).



                    Note: For c++11 or greater, contrexpr is recommended.






                    share|improve this answer






















                    • 3





                      This reasoning is wrong. Compiler optimizations have not happened at the point where the compiler decides whether the code is valid or not. And you get the same error even without any optimizations. Further, value1 is definitely not opaque to compiler optimizations. It's just that value2 is a constant expression while value1 is not.

                      – Max Langhof
                      9 hours ago












                    • Corrected, @MaxLanghof

                      – v78
                      8 hours ago













                    -4














                    -4










                    -4









                    #include <iostream>
                    #include <vector>


                    int main()
                    int value1 = 12;
                    char c1value1; // error! no narrowing

                    const int value2 = 12;
                    char c2value2; // why is this fine?



                    Warning thrown by your program.



                    test.cpp: In function ‘int main()’:
                    test.cpp:7:19: warning: narrowing conversion of ‘value1’ from ‘int’ to ‘char’ inside [-Wnarrowing]
                    char c1value1; // error! no narrowing
                    ^


                    Its happens because const int 12 is optimized by compiler to literal 12. While int value1 is not compile time constant(although known at compile time in this case).



                    Note: For c++11 or greater, contrexpr is recommended.






                    share|improve this answer















                    #include <iostream>
                    #include <vector>


                    int main()
                    int value1 = 12;
                    char c1value1; // error! no narrowing

                    const int value2 = 12;
                    char c2value2; // why is this fine?



                    Warning thrown by your program.



                    test.cpp: In function ‘int main()’:
                    test.cpp:7:19: warning: narrowing conversion of ‘value1’ from ‘int’ to ‘char’ inside [-Wnarrowing]
                    char c1value1; // error! no narrowing
                    ^


                    Its happens because const int 12 is optimized by compiler to literal 12. While int value1 is not compile time constant(although known at compile time in this case).



                    Note: For c++11 or greater, contrexpr is recommended.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited 9 hours ago

























                    answered 9 hours ago









                    v78v78

                    1,9669 silver badges21 bronze badges




                    1,9669 silver badges21 bronze badges










                    • 3





                      This reasoning is wrong. Compiler optimizations have not happened at the point where the compiler decides whether the code is valid or not. And you get the same error even without any optimizations. Further, value1 is definitely not opaque to compiler optimizations. It's just that value2 is a constant expression while value1 is not.

                      – Max Langhof
                      9 hours ago












                    • Corrected, @MaxLanghof

                      – v78
                      8 hours ago












                    • 3





                      This reasoning is wrong. Compiler optimizations have not happened at the point where the compiler decides whether the code is valid or not. And you get the same error even without any optimizations. Further, value1 is definitely not opaque to compiler optimizations. It's just that value2 is a constant expression while value1 is not.

                      – Max Langhof
                      9 hours ago












                    • Corrected, @MaxLanghof

                      – v78
                      8 hours ago







                    3




                    3





                    This reasoning is wrong. Compiler optimizations have not happened at the point where the compiler decides whether the code is valid or not. And you get the same error even without any optimizations. Further, value1 is definitely not opaque to compiler optimizations. It's just that value2 is a constant expression while value1 is not.

                    – Max Langhof
                    9 hours ago






                    This reasoning is wrong. Compiler optimizations have not happened at the point where the compiler decides whether the code is valid or not. And you get the same error even without any optimizations. Further, value1 is definitely not opaque to compiler optimizations. It's just that value2 is a constant expression while value1 is not.

                    – Max Langhof
                    9 hours ago














                    Corrected, @MaxLanghof

                    – v78
                    8 hours ago





                    Corrected, @MaxLanghof

                    – v78
                    8 hours ago


















                    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%2f57855180%2fwhy-is-const-int-fine-for-char-brace-init%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

                    Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                    Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                    François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480