Const and CONSTEXPR

Source: Internet
Author: User

We already know that the const variable cannot be modified. C + + also provides a more "strict" constexpr specifier (constexpr-specifier), when a variable is declared or defined, if the type specifier is preceded or followed by a constexpr specifier, Indicates that the variable is a const variable and that the variable must be initialized. The expression used to initialize the variable must be a "constant expression", even more restrictive than const,constexpr. This means that the CONSTEXPR variable is a const variable initialized by a constant expression. For basic data types, a constant expression is an expression consisting of a literal constant, a variable that is constexpr, and a const variable initialized by a constant expression. In other words, the value of a constant expression can be determined during compilation. For example

    1. int nonconst_var = 100;   
    2. const int const_var1  = 2;   
    3. const  INT CONST_VAR2 = NONCONST_VAR;   
    4. constexpr int constexpr_var1 = 3 + const_var1 *  4; //established   
    5. constexpr int constexpr_var2 = 3 + nonconst_var * 4; //error   
    6. constexpr int  Constexpr_var3 = 3 + const_var2 * 4; //error  

Const and CONSTEXPR

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.