Question:

What are macros and inline functions in C++? ?

by  |  earlier

0 LIKES UnLike

Consider the following example and explain where they are used and why they are used.

#include <iostream.h>

#define MAX( A, B ) ((A) > (B) ? (A) : (B))

inline int max( int a, int b )

{

if ( a > b )

return a;

return b;

}

void main()

{

int i, x, y;

x = 23; y = 45;

i = MAX( x++, y++ ); // Side-effect:

// larger value incremented twice

cout << "x = " << x << " y = " << y << '\n';

x = 23; y = 45;

i = max( x++, y++ ); // Works as expected

cout << "x = " << x << " y = " << y << '\n';

}

 Tags:

   Report

1 ANSWERS


  1. Hi,

    First, macroses help make your code look shorter (and more inteligeable)

    Second, to understand why your variables are getting incemented by 1 twice (instead of only once), lets unfold the exprtession with the macros (e.g. do the job the C++ precompiler does every time when you compile your application):

    i = MAX( x++, y++ ); //(before)

    i = ((x++) &gt; (y++) ? (x++) : (y++)) ; //after

    As you can see, the y++ operator executes twice (first before the comparison to x++ and second after it is assigned to the variable i)

    That&#039;s why you will receive 47 instead of &quot;46&quot;

    To make it work as you expect, you should first make the ++ operation, and then use the macros, like so:

    int x2, y2;

    x2 = x++; y2=y++;

    i=MAX(x2,y2);

    Afterword: Macroses, as opposed to functions/procedures, usually execute faster, because they are not compiled to procedures/functions, but are unravelled into code (inline), but they might make your progmam bigger in size. Consider using them in cycles/loops where speed is a decisive factor

Question Stats

Latest activity: earlier.
This question has 1 answers.

BECOME A GUIDE

Share your knowledge and help people by answering questions.