Created
July 31, 2019 05:43
-
-
Save qiaoxu123/c430cace0206e43155fde86c30b398ec to your computer and use it in GitHub Desktop.
[参考链接](https://qiaoxu123.github.io/post/3-C++Courses/)
`const`变量在C/C++中有较大的区别。对于C语言来讲,`const`定义仅仅是一个只读变量,可以通过指针进行修改。而C++中对`const`参数进行了升级处理,使用类似宏定义的方式进行了常量化。为了向上兼容,也保留了原有的一些性质。具体看参考链接。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
int main(){ | |
const int c = 0; | |
int* p = (int*)&c; | |
printf("Begin...\n"); | |
*p = 5; | |
printf("c = %d\n",c); | |
printf("End...\n"); | |
return 0; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
using namespace std; | |
void f(){ | |
#define a 3 //此处为预处理,在编译之前已经将所有a都进行了替换 | |
const int b = 4; | |
} | |
void g(){ | |
printf("a = %d\n",a); //此处a已经进行了替换 | |
//printf("b = %d\n",b); | |
} | |
int main(){ | |
const int A = 1; | |
const int B = 1; | |
int array[A + B] = {0};//此处若用C语言编译器,则报错。因为数组大小定义使用变量 | |
int i = 0; | |
for(i = 0;i < (A + B);++i) | |
printf("array[%d] = %d\n",i,array[i]); | |
f(); | |
g(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment