Learn C + + from C to C + + (const qualifier) with me

Source: Internet
Author: User

Const qualifier

1. Use const to give literal constants a name (identifier), which is called an identifier constant, because the declaration and usage of an identifier constant is much like a variable, so it is also called a constant variable

2. General form of definition:

(1) const data type constant name = constant value;

(2) Data type const constant name = constant value;

3. For example: const float pi=3.14159f;

4. Precautions:

(1) Constant variables must be initialized at the time of definition;

(2) After initialization of the constant variable, it is not allowed to be assigned again;

code example:

Main.cpp#include <iostream>using namespace std;//introduces namespace int main (void) {//const int a;//1.error, constants must initialize const int a = 100;//A = 200;//2.error, constants cannot be re-assigned int b = 22;const int * P;//const on the left, indicating *p as constant, via *p cannot change what the pointer points to P = &b;//*p = 20 0;//2.error, constants cannot be re-assigned//int * Const P2;//1.ERROR,P2 is constant, constants must initialize int * Const P2 = &b;//const on * Right, P2 is constant//int c =100;// P2 = &c;//2.error, constants cannot be re-assigned *P2 = 200;cout<<b<<endl;cout<<*p<<endl;return 0;}


Error usage compilation error message:

1. constintA;

error C2734: "A": if it is not external, you must initialize the constant object

2. constinta = 100; a = 200;

error C3892: "A": cannot assign a value to a constant


Learn C + + from C to C + + (const qualifier) with me

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.