📜  C++中内联和宏的区别

📅  最后修改于: 2021-09-12 11:27:27             🧑  作者: Mango

1. 内联:
内联函数是由inline关键字定义的普通函数。内联函数是由编译器扩展的短函数。并且它的参数只被评估一次。内联函数是短长度的函数,它们在类中不使用inline关键字而自动成为内联函数。

内联函数的语法:

inline return_type function_name ( parameters )
{ 
 // inline function code
}

内联函数示例:

#include 
using namespace std;
  
// Inline function
inline int Maximum(int a, int b)
{
    return (a > b) ? a : b;
}
  
// Main function for the program
int main()
{
    cout << "Max (100, 1000):" << Maximum(100, 1000) << endl;
    cout << "Max (20, 0): " << Maximum(20, 0) << endl;
  
    return 0;
}

输出:

Max (100, 1000): 1000
Max (20, 0): 20 

2. 宏:
它也称为预处理器指令。宏由#define关键字定义。在程序编译之前,只要预处理器检测到宏,预处理器就会检查程序,然后预处理器用宏定义替换宏。

宏的语法:

#define MACRO_NAME Macro_definition 

宏示例:

#include 
using namespace std;
  
// macro with parameter
#define MAXIMUM(a, b) (a > b) ? a : b
  
// Main function for the program
int main()
{
    cout << "Max (100, 1000):";
    int k = MAXIMUM(100, 1000);
    cout << k << endl;
  
    cout << "Max (20, 0):";
    int k1 = MAXIMUM(20, 0);
    cout << k1;
  
    return 0;
}

输出:

Max (100, 1000):1000
Max (20, 0):20 

C++中内联和宏的区别:

S.NO Inline Macro
1. An inline function is defined by the inline keyword. Whereas the macros are defined by the #define keyword.
2. Through inline function, the class’s data members can be accessed. Whereas macro can’t access the class’s data members.
3. In the case of inline function, the program can be easily debugged. Whereas in the case of macros, the program can’t be easily debugged.
4. In the case of inline, the arguments are evaluated only once. Whereas in the case of macro, the arguments are evaluated every time whenever macro is used in the program.
5. In C++, inline may be defined either inside the class or outside the class. Whereas the macro is all the time defined at the beginning of the program.
6. In C++, inside the class, the short length functions are automatically made the inline functions. While the macro is specifically defined.
7. Inline is not as widely used as macros. While the macro is widely used.
8. Inline is not used in competitive programming. While the macro is very much used in competitive programming.
9. Inline function is terminated by the curly brace at the end. While the macro is not terminated by any symbol, it is terminated by a new line.
想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解基础加 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程