c语言中的宏函数及c++的内联函数及auto及NULL

 c++的内联函数

使用内联函数可以减少函数栈帧的开销。

	Swap(a, b);
00A516C8  mov         eax,dword ptr [a]  
00A516CB  mov         dword ptr [ebp-20h],eax  
00A516CE  mov         ecx,dword ptr [b]  
00A516D1  mov         dword ptr [a],ecx  
00A516D4  mov         edx,dword ptr [ebp-20h]  
00A516D7  mov         dword ptr [b],edx  

 内联函数会在调用它的地方展开。(展开及不会call 函数名)

inline void Swap(int& x, int& y)
{
	int tmp = x;
	x = y;
	y = tmp;
}
int main()
{
	int a = 1, b = 2;
	Swap(a, b);
	cout << a << b << endl;
	return 0;
}

特性

1. inline是一种以空间换时间的做法,省去调用函数额开销。所以代码很长或者有循环/递归的函数不适宜 使用作为内联函数。

2. inline对于编译器而言只是一个建议,编译器会自动优化,如果定义为inline的函数体内有循环/递归等 等,编译器优化时会忽略掉内联。

3. inline不建议声明和定义分离,分离会导致链接错误。因为inline被展开,就没有函数地址了,链接就会 找不到。

vs2022查看反汇编代码

在 Visual Studio 中查看反汇编代码_vs2022反汇编-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/qq_27843785/article/details/107189963内联函数如果超过30行左右编译器会自动去除内联。

C++有哪些技术替代宏?

1. 常量定义 换用const

2. 函数定义 换用内联函数

 auto不能推导的场景

1. auto不能作为函数的参数

// 此处代码编译失败,auto不能作为形参类型,因为编译器无法对a的实际类型进行推导
void TestAuto(auto a)
{}

2.auto不能直接用来声明数组

void TestAuto()
{
 int a[] = {1,2,3};
 auto b[] = {4,5,6};
}

使用范围for 的前提:数组         数组的指针不行(void TestFor(int array[]) )

void TestFor()
{
 int array[] = { 1, 2, 3, 4, 5 };
 for(auto& e : array)
 e *= 2;
 
 for(auto e : array)
 cout << e << " ";
 
 return 0;
}

NULL

NULL实际是一个宏,在传统的C头文件(stddef.h)中,可以看到如下代码:

#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif

 c语言中的宏函数

gcc -E test.c -o test.i
#include<stdio.h>
#define MAX(x,y)  ((x)>(y)?(x):(y))
int main()
{
    int a=1,b=2;
    int m=MAX(a,b);
    printf("MAX: %d\n",m);
    return 0;
}

预处理后:

int main()
{
    int a=1,b=2;
    int m=((a)>(b)?(a):(b));
    printf("MAX: %d\n",m);
    return 0;
}

gcc: fatal error: no input files compilation terminated.

 【Linux】11. 常见操作错误的解决办法_gcc: fatal error: no input files-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/WL0616/article/details/121225484

Makefile:2: *** missing separator.  Stop. 

test:test.c
    gcc -o $@ $^ 
.PHONY:clean
clean:
    rm -f test

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值