The const of thinking in idle time

Source: Internet
Author: User

For most people, the const usage, such as the modified return value and the modifier parameters, should be very well understood and I'm going to discuss


For the C language

#include <stdio.h>void main () {const int A=10;int *p = (int*) &a;*p = 100;printf ("%d\n", a);}

Top Output 100

For C + +,

#include <iostream>using namespace Std;void main () {const int A=10;int *p = (int*) &a;*p = 100;printf ("%d\n", a);}
Top Output 10


What is the reason, C is a const is a variable can not be changed, there is memory space allocation, so you can change in memory through the address

The const in C + + is a constant, which is usually stored in the character table, not allocating memory, but reassigning a variable with the same name as the const constant at the time of bearing the variable or looking at the address of the variable, so the address of the output at this time is the address of the new variable. So the value of this variable is changed by address, but the compiler will read the value of the constant in the symbol table, so the value does not change.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The const of thinking in idle time

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.