Const in C + +

Source: Internet
Author: User

First look at a program like this:

1#include <iostream>2 using namespacestd;3 intMain () {4     Char*s ="Hello World";5 6cout << S <<Endl;7s[0] ='B';8cout << S <<Endl;9     return 0;Ten}

The result of compiling the run under VS2013 is:

What's the reason?

The memory in the computer is partitioned (Segment) when it is used for programming, and is divided into: stack, heap, global (static), literal constant, and code area.

Strings defined with *s are stored in the literal constant area, which is defaulted to the const type and therefore cannot be modified.

When the program is changed to the following, you can get the desired effect.

1#include <iostream>2 using namespacestd;3 intMain () {4     //char *s = "Hello World";5     CharS[] ="Hellow World";6cout << S <<Endl;7s[0] ='B';8cout << S <<Endl;9      while(1);Ten     return 0; One}

Operation Result:

By printing the first address of the string in two ways, it is easy to spot the problem.

The Modified program:

1#include <iostream>2 using namespacestd;3 intMain () {4     Char*S1 ="Hello World";5     CharS2[] ="Hellow World";6cout << &s1 <<Endl;7     //s[0] = ' B ';8cout << &s2 <<Endl;9cout << &main <<Endl;Ten      while(1); One     return 0; A}

Operation Result:

The string defined by the string is found to be placed in a very forward address space (the stack area), and the string defined by the pointer is close to the main function address.

Const in C + +

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.