标签:c++ primer c++ c语言

#include <iostream>
using namespace std;
int main(void)
{
bool result;
//result = true;
result = 100;
cout << result << endl;
return 0;
}#include <iostream>
using namespace std;
int main(void)
{
//const int a; Error,常量必须初始化
const int a = 100;
//a = 200; Error,常量不能重新被赋值
int b = 22;
const int * p; //const在*左边,表示*p为常量,经由*p不能更改指针所指向的内容
p = &b;
//*p = 200; Error,常量不能重新被赋值
//int * const p2; Error,p2为常量,常量必须初始化
int * const p2 = &b; //const在*右边,表示p2为常量
//int c =100;
//p2 = &c; Error,常量不能重新被赋值
*p2 = 200;
cout << b << endl;
return 0;
}#include<iostream>
using namespace std;
#define STR(a) #a
#define CAT(a,b) a##b
int main(void)
{
int xy = 100;
cout << STR(ABCD) << endl; // #ABCD => "ABCD" //表示对a加上双引号,一个#表示那个位置用宏参数作为字符串代替
cout << CAT(x, y) << endl; // x##y => xy //表示x连接y,两个##意思就是将##两端的字符串拼接起来
return 0;
}
//Effective C++ 3rd的一个例子。 #define CALL_WITH_MAX(a,b) f((a) > (b) ? (a) : (b)) int a = 5; int b = 0; CALL_WITH_MAX(++a, b); //a被累加二次 CALL_WITH_MAX(++a, b+10); //a被累加一次
在这里,调用f之前,a的递增次数竟然取决于“它被拿来和谁比较”
4、定义常量还可以用enum,尽量用const、enum替换#define定义常量。
首先重新回顾一下关于类/对象大小的计算原则:
#include <iostream>
using namespace std;
#include <stdio.h>
struct Test
{
char a;
double b;
};
int main(void)
{
cout<<sizeof(Test)<<endl;
return 0;
}#include <iostream>
using namespace std;
#include <stdio.h>
#pragma pack(2)
struct Test
{
char a;
double b;
char c;
};
#pragma pack()
//第一个成员与结构体变量的偏移量为0
//其它成员要对齐到某个数字(对齐数)的整倍数的地址
//对齐数取编译器预设的一个对齐整数与该成员大小的较小值
//结构体总大小为最大对齐数的整数倍
int main(void)
{
Test test;
//&test == &test.a;
char *p= (char*)&test;
//cout<<p<<endl;
printf("p=%p\n", p);
p = &test.a;
printf("p=%p\n", p);
cout<<sizeof(Test)<<endl;
return 0;
}#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
struct A
{
long a1;
short a2;
int a3;
int* a4;
};
int main()
{
cout << sizeof(A) << endl;
}#include <stdint.h>
#include <stdio.h>
union X
{
int32_t a;
struct
{
int16_t b;
int16_t c;
};
};
int main()
{
X x;
x.a = 0x20150810;
printf("%x,%x\n", x.b, x.c);
return 0;
}参考:
C++ primer 第四版
C++ primer 第五版
版权声明:本文为博主原创文章,未经博主允许不得转载。
C++ Primer 学习笔记_15_从C到C++(1)--bool类型、const限定符、const与#define、结构体内存对齐
标签:c++ primer c++ c语言
原文地址:http://blog.csdn.net/keyyuanxin/article/details/48829087