在C语言横行的时代,为了加快运行速度,一些关键变量会被放入寄存器中,程序代码请求编译器把变量存入寄存器,然而C语言版的寄存器变量没法经过地址得到register变量。
c++仍然支持关键字register
#include "iostream" #include<string> using namespace std; void main() { for (int i = 0; i < 10000; i++) { printf("%d\n", i);//这种状况下就会把i放入寄存器,由于i被频繁使用 } system("pause"); }
#include "iostream" #include<string> using namespace std; void main() { register string a = "陈培昌"; printf("变量地址为%d\n", &a); system("pause"); }
输出结果:ios
#include "iostream" #include<string> using namespace std; void main() { string a; string a = "陈培昌"; printf("教练姓名%s\n", a); system("pause"); }
所谓变量检测的加强就是c++不容许重复声明变量,而C能够(不过windows下vs2013报错,由于c/c++一直在避免这种二义性)c++
C语言中,struct结构是一组变量的集合,不认为它是一种新的类型,说的通俗点windows
#include<stdio.h> struct mycoach { char name[100]; int age; }; void main() { struct mycoach cpc;//不加struct关键字报错 }
C++中数据结构
struct mycoach { string name; int age; }; void main() { mycoach cpc;//竟然能够 system("pause"); }
一些状况下,struct跟类有殊途同归之妙函数
#include "iostream" #include<string> using namespace std; struct mycoach { public: string name; int age; private: string favorite; }; void main() { mycoach cpc; system("pause"); }
#include "iostream" #include<string> using namespace std; void main() { bool w=true; printf("布尔变量长度%d\n", sizeof(w)); w = -9; printf("布尔值为%d\n", w); w = 8; printf("布尔值为%d\n", w); w = 0; printf("布尔值为%d\n", w); system("pause"); }
若是多个布尔值同时声明,可能占用一个bit,取决于编译器的实现spa
bool b2,b3,b4;3d
C语言中,表达式的返回值放到了CPU寄存器里面,是一个值(数),而c++返回的是变量的自己
c++指针
void main() { int a = 20; int b = 10; (a < b ? a : b) = 30;//至关于执行b=30; printf("值b为:%d\n", b); system("pause"); }
然而c语言中code
究其缘由是C语言返回了b的值,因此(a<b?a:b)=30最后执行的命令是10=30;这样一来操做就变得毫无心义;听说这个例子是说明C和c++编译器不一样的有力案例blog
c++如何作到的?看来是返回了地址......,因此c语言的代码不妨修改以下:
#include<stdio.h> void main() { int a = 20; int b = 10; *(a < b?&a :&b) = 30; printf("值b为:%d\n", b); system("pause"); }
输出结果:
#include<iostream> using namespace std; struct mycoach { string name; int age; }; int opcoach01(mycoach* const pt) { //指针变量自己不能被修改 pt->name = "陈培昌"; pt = NULL; } int opcoach02(const mycoach *pt) { //指针指向的内存空间不能被修改 pt->name = "陈培昌"; }
输出结果:
#include<stdio.h> void main() { const int a = 20; a = 30; printf("值a为:%d\n", a); system("pause"); }
输出结果:
然而:
#include<stdio.h> void main() { const int a = 20; int *p = NULL; p =&a; *p = 30; printf("值a为:%d\n", a); getchar(); }
这样一来:
所以在c语言中const是个伪常量;而c++没法这样修改,由于c++编译器扫描到const类型时,并不像c语言那样为其分配内存,而是放入符号表(一种键值对类型的数据结构)
有别于C语言内存四区
c++编译器扫描到对常量取地址操做时,为常量分配内存空间
或者const变量做为一种全局变量使用时,也会分配内存空间
c++ const类型实现机制
取值时,从符号表里读取a对应的变量
执行 p=int(*)&a操做时,另开辟了一块空间,让整型指针p指向这块空间的地址
下列代码证明p指向的空间存在
#include<iostream> using namespace std; void main() { const int a = 30; int *p = NULL; p = (int*)&a; *p = 40; printf("a的值依旧是:%d\n",a); cout << "p指向的空间真实存在,其内存地址是" << p << "值是:" << *p<<endl; system("pause"); }
输出结果: