c++ 常用的一些宏定义

2023-12-13 08:22:11
#include<iostream>
#include <windows.h>
#include <string>
using namespace std;


#define Conn(x,y) x##y   //表示x连接y
#define tochar(x) #@x //给x加上单引号,结果返回是一个const char
#define tostring(x) #x  //给x加双引号 返回char const *

#define MEM_B(x)(*((byte*)(x))) //得到指定地址上的一个字节
#define MEM_W(x)(*((WORD*)(x))) //得到指定地址上的一个字  WORD 16-bit unsigned integer DWORD 32 - bit unsigned integer
#define OFFSETOF(type,field) ((size_t)& ((type*)0)->field)  //得到一个field在结构体(struct type)中的偏移量。
#define FSIZ(type,field) sizeof( ((type *) 0)->field )  // 得到一个结构体中field所占用的字节数 

//得到一个变量的地址(word宽度)
#define B_PTR( var ) ( (byte *) (void *) &(var) )  
#define W_PTR( var ) ( (WORD *) (void *) &(var) )

#define UPCASE( c ) ( ((c) >= 'a' && (c) <= 'z') ? ((c) - 0x20) : (c) ) //将一个字母转换为大写
#define INC_SAT( val ) (val = ((val)+1 > (val)) ? (val)+1 : (val)) //防止溢出的一个方法
#define ARR_SIZE( a ) ( sizeof( (a) ) / sizeof( (a[0]) ) ) //返回数组的个数


//ANSI标准说明了五个预定义的宏名。它们是:
#define _LINE_ __LINE__ /*(两个下划线),对应%d*/
//_FILE_ /*对应%s*/
//_DATE_ /*对应%s*/
//_TIME_ /*对应%s*/

struct Person 
{
	string name;
	int age;
};

void test01()
{
	cout << Conn(123, 444) << endl; //123444
	cout << Conn("abc", "efg") << endl; //abcefg


	auto a2 = tochar(4);
	cout << a2 << endl;  // a2='4'
	cout << typeid(a2).name() << endl;


	auto a3 = tostring(43434);
	cout << a3 << endl; //a3="43434"
	cout << typeid(a3).name() << endl;

	int bTest = 0x123456; //0001 0010 0011 0100 0101 0110
	byte m = MEM_B((&bTest));
	cout << int(m) << endl;//86 = 0101 0110  一个字节8bit

	int n = MEM_W((&bTest));/*n=0x3456*/
	cout << int(n) << endl;   //13398  = 0011 0100 0101 0110  一个WORD 16bit

	struct Person p = { "dsd",88 };
	cout << OFFSETOF(Person, name) << endl; //0
	cout << OFFSETOF(Person, age) << endl; //28
	cout << FSIZ(Person, age) << endl; //4
	cout << FSIZ(Person, name) << endl; //28

	int num = 97;
	cout << B_PTR(num) << endl;  // a 97
	cout << W_PTR(num) << endl;  //0019FD98

	cout << UPCASE('a') << endl; //65  = A
	int num1 = 99;
	int num2 = 99999999999999999;
	cout << INC_SAT(num1) << endl; //100
	cout << INC_SAT(num2) << endl; //1569325056

	int arr[] = { 1,2,43,5 };
	int arr1[][4] =
	{
		{1, 2, 3, 5},
		{ 1,2,3,5 },
	};
	cout << ARR_SIZE(arr) << endl; //4
	cout << ARR_SIZE(arr1) << endl; //2

	int x = 0;
	int y = 10;
	if (y > x) {
		printf("Error: y is greater than x at line %d\n", _LINE_);
	}
}



int main()
{	
	test01();
	system("pause");
	return 0;
}

文章来源:https://blog.csdn.net/sanqianshijie/article/details/134955376
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。