C++ Self-study - Inline Functions

Inline functions are inline extensions used to eliminate the time overhead of function calls. It is usually used for frequently executed functions

If you need to perform an operation frequently, you can use inline to define it.

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <shappmgr.h>
#include <stdio.h>

using namespace std;

inline bool isnumber(char ch) {
	return ((ch >= '0') && (ch <= '9'));
}

int main() {
	char a;
	while ((a = cin.get()) != '\n') {
		if (isnumber(a))
		{
			cout << "You entered a number between 0-9" << endl;
		}
		else {
			cout << "You entered a number other than 0-9" << endl;
		}
	}
	return 0;
}

  But inline functions cannot contain complex keywords (such as while, switch), if so, the compiler will ignore these definitions and continue to generate the same calling code for the following calls.

Recursive functions cannot be used for inline functions,

In many cases, inline functions are limited to small and frequently called functions.

Inline function and macro definition

  • Macro definitions can replace small function definitions, but have flaws
  • The macro just tells the compiler to substitute the code, it doesn't check the parameter type
  • Often can't actually be parsed into what the code wants
  • What the macro does can be replaced with an inline function:
    #define MAX(a,b)((a)>(b)?a:b))
    

      

 

This can be replaced with an inline function:

inline int MAX(int a,int b){
    return a>b?a:b
}

Example

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <shappmgr.h>
#include <stdio.h>

using namespace std;

inline int tobiger(int a, int b) {
	return a > b ? a : b;
}
inline int tosmall(int a, int b) {
	return a < b ? a : b;
}
int main() {
	int a = 10;
	int b = 11;
	cout << tobiger(a,b)<< endl;
	cout << tosmall(a, b) << endl;
	a = a + a;
	cout << tobiger(a++, b) << endl;
	cin.get();
	return 0;
}

  output:

11

10

20

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324651439&siteId=291194637