Programing

인라인 함수와 전 처리기 매크로

crosscheck 2020. 8. 7. 07:59
반응형

인라인 함수와 전 처리기 매크로


인라인 함수는 전 처리기 매크로와 어떻게 다릅니 까?


전 처리기 매크로는 코드에 적용된 대체 패턴 일뿐입니다. 컴파일이 시작되기 전에 확장으로 대체되기 때문에 코드의 거의 모든 곳에서 사용할 수 있습니다.

인라인 함수는 본문이 호출 사이트에 직접 삽입되는 실제 함수입니다. 함수 호출이 적절한 경우에만 사용할 수 있습니다.

이제 함수와 같은 컨텍스트에서 매크로 대 인라인 함수를 사용하는 한 다음 사항에 유의하십시오.

  • 매크로는 형식에 안전하지 않으며 구문 적으로 올바른지 여부에 관계없이 확장 할 수 있습니다. 컴파일 단계에서는 매크로 확장 문제로 인한 오류를보고합니다.
  • 예상치 못한 상황에서 매크로를 사용하면 문제가 발생할 수 있습니다.
  • 매크로는 다른 매크로를 확장 할 수 있다는 점에서 더 유연합니다. 반면 인라인 함수가 반드시이 작업을 수행하는 것은 아닙니다.
  • 매크로는 확장으로 인해 부작용이 발생할 수 있습니다. 입력 표현식은 패턴에 나타날 때마다 복사되기 때문입니다.
  • 인라인 함수가 항상 인라인되는 것이 보장되는 것은 아닙니다. 일부 컴파일러는 릴리스 빌드에서만이 작업을 수행하거나 그렇게하도록 특별히 구성된 경우에만 수행합니다. 또한 경우에 따라 인라이닝이 불가능할 수 있습니다.
  • 인라인 함수는 변수 (특히 정적)에 대한 범위를 제공 할 수 있으며, 전 처리기 매크로는 코드 블록 {...}에서만이를 수행 할 수 있으며 정적 변수는 정확히 동일한 방식으로 작동하지 않습니다.

첫째, 전 처리기 매크로는 컴파일 전에 코드에서 "복사 붙여 넣기"일뿐입니다. 따라서 유형 검사 가 없으며 일부 부작용 이 나타날 수 있습니다.

예를 들어 두 값을 비교하려는 경우 :

#define max(a,b) ((a<b)?b:a)

max(a++,b++)예를 들어 사용하면 부작용이 나타납니다 ( a또는 b두 번 증가합니다). 대신 (예 :)

inline int max( int a, int b) { return ((a<b)?b:a); }

Inline 함수는 컴파일러에 의해 확장되며, 매크로는 전처리기에 의해 확장되며 이는 단순한 텍스트 대체입니다.

  • 함수 호출 중에 유형 검사가 수행되는 동안 매크로 호출 중에 유형 검사가 없습니다.

  • 인수 및 작업 순서의 재평가로 인해 매크로 확장 중에 원하지 않는 결과와 비 효율성이 발생할 수 있습니다. 예를 들어

    #define MAX(a,b) ((a)>(b) ? (a) : (b))
    int i = 5, j = MAX(i++, 0);
    

    결과

    int i = 5, j = ((i++)>(0) ? (i++) : (0));
    
  • 매크로 인수는 매크로 확장 전에 평가되지 않습니다.

    #define MUL(a, b) a*b
    int main()
    {
      // The macro is expended as 2 + 3 * 3 + 5, not as 5*8
      printf("%d", MUL(2+3, 3+5));
     return 0;
    }
    // Output: 16`
    
  • return 키워드는 함수의 경우처럼 값을 반환하기 위해 매크로에서 사용할 수 없습니다.

  • 인라인 함수는 오버로드 될 수 있습니다.

  • 매크로에 전달 된 토큰은 Token-Pasting operator라는 연산자 ##을 사용하여 연결할 수 있습니다.

  • 매크로는 일반적으로 인라인 함수를 사용하여 함수 호출 (서브 루틴으로의 점프 방지) 중에 시간 오버 헤드 (초과 시간)를 제거하는 코드 재사용에 사용됩니다.


주요 차이점은 유형 검사입니다. 컴파일러는 입력 값으로 전달하는 것이 함수에 전달할 수있는 유형인지 확인합니다. 이는 전 처리기 매크로의 경우 사실이 아닙니다. 유형 검사 전에 확장되어 버그를 감지하기 어렵고 심각 할 수 있습니다.

여기 에 몇 가지 덜 분명한 요점이 설명되어 있습니다.


이미 주어진 것들에 또 다른 차이점을 추가하려면 #define디버거에서 단계를 수행 할 수 없지만 인라인 함수를 통해 단계를 수행 할 수 있습니다.


매크로는 네임 스페이스를 무시합니다. 그리고 그것은 그들을 사악하게 만듭니다.


인라인 함수는 매크로와 유사합니다 (함수 코드는 컴파일 타임에 호출 지점에서 확장되기 때문). 인라인 함수는 컴파일러에 의해 구문 분석되는 반면 매크로는 전처리기에 의해 확장됩니다. 결과적으로 몇 가지 중요한 차이점이 있습니다.

  • 인라인 함수는 일반 함수에 적용되는 유형 안전의 모든 프로토콜을 따릅니다.
  • 인라인 함수는 함수 선언에 인라인 키워드를 포함한다는 점을 제외하고는 다른 함수와 동일한 구문을 사용하여 지정됩니다.
  • 인라인 함수에 인수로 전달 된 표현식은 한 번 평가됩니다.
  • 경우에 따라 매크로에 인수로 전달 된 식을 두 번 이상 평가할 수 있습니다. http://msdn.microsoft.com/en-us/library/bf6bf4cf.aspx

  • 매크로는 사전 컴파일 시간에 확장되므로 디버깅에 사용할 수 없지만 인라인 함수를 사용할 수 있습니다.

- 좋은 기사 : http://www.codeguru.com/forum/showpost.php?p=1093923&postcount=1

;


인라인 함수는 값 의미를 유지하는 반면 전 처리기 매크로는 구문을 복사합니다. 인수를 여러 번 사용하면 전 처리기 매크로로 매우 미묘한 버그를 얻을 수 있습니다. 예를 들어 인수에 "i ++"와 같은 변형이 포함되어 있으면 두 번 실행되는 것은 상당히 놀라운 일입니다. 인라인 함수에는이 문제가 없습니다.


A inline functuion behaves syntactically just like a normal function, providing type safety and a scope for function local variables and access to class-members if it is a method. Also when calling inline methods you must adhere to private/protected restrictions.


In GCC (I'm not sure about others), declaring a function inline, is just a hint to the compiler. It is still up to the compiler at the end of the day to decide whether or not it includes the body of the function whenever it is called.

The difference between in-line functions and preprocessor macros is relatively large. Preprocessor macros are just text replacement at the end of the day. You give up a lot of the ability for the compiler to perform checking on type checking on the arguments and return type. Evaluation of the arguments is much different (if the expressions you pass into the functions have side-effects you'll have a very fun time debugging). There are subtle differences about where functions and macros can be used. For example if I had:

#define MACRO_FUNC(X) ...

Where MACRO_FUNC obviously defines the body of the function. Special care needs to be taken so it runs correctly in all cases a function can be used, for example a poorly written MACRO_FUNC would cause an error in

if(MACRO_FUNC(y)) {
 ...body
}

A normal function could be used with no problem there.


From the perspective of coding, an inline function is like a function. Thus, the differences between an inline function and a macro are the same as the differences between a function and a macro.

From the perspective of compiling, an inline function is similar to a macro. It is injected directly into the code, not called.

In general, you should consider inline functions to be regular functions with some minor optimization mixed in. And like most optimizations, it is up to the compiler to decide if it actually cares to apply it. Often the compiler will happily ignore any attempts by the programmer to inline a function, for various reasons.


inline functions will behave as a function call if there exists any iterative or recursive statement in it, so as to prevent repeated execution of instructions. Its quite helpful to save the overall memory of your program.


#include<iostream>
using namespace std;
#define NUMBER 10 //macros are preprocessed while functions are not.
int number()
{ 
    return 10;
}
/*In macros, no type checking(incompatible operand, etc.) is done and thus use of micros can lead to errors/side-effects in some cases. 
However, this is not the case with functions.
Also, macros do not check for compilation error (if any). Consider:- */
#define CUBE(b) b*b*b
int cube(int a)
{
 return a*a*a;
}
int main()
{
 cout<<NUMBER<<endl<<number()<<endl;
 cout<<CUBE(1+3); //Unexpected output 10
 cout<<endl<<cube(1+3);// As expected 64
 return 0;
}

Macros are typically faster than functions as they don’t involve actual function call overhead.

Some Disadvantages of macros: There is no type checking.Difficult to debug as they cause simple replacement.Macro don’t have namespace, so a macro in one section of code can affect other section. Macros can cause side effects as shown in above CUBE() example.

Macros are usually one liner. However, they can consist of more than one line.There are no such constraints in functions.

참고URL : https://stackoverflow.com/questions/1137575/inline-functions-vs-preprocessor-macros

반응형