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

📅  最后修改于: 2021-05-30 04:57:25             🧑  作者: 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等的更多准备工作,请参阅“完整面试准备课程”