Although inline functions are similar to macros (because the function code is expanded at the point of the call at compile time), inline functions are parsed by the compiler, whereas macros are expanded by the preprocessor. As a result, there are several important differences:
#include <stdio.h>
#include <conio.h>
#define toupper(a) ((a) >= 'a' && ((a) <= 'z') ? ((a)-('a'-'A')):(a))
void main()
{
char ch = toupper( _getch() );
printf( “%c”, ch );
}
The intent of the expression toupper( _getch() )
is that a character should be read from the console device (stdin) and, if necessary, converted to uppercase.
Because of the implementation, _getch is executed once to determine whether the character is greater than or equal to “a,” and once to determine whether it is less than or equal to “z.” If it is in that range, _getch is executed again to convert the character to uppercase. This means the program waits for two or three characters when, ideally, it should wait for only one.
Inline functions remedy this problem:
#include <stdio.h>
#include <conio.h>
inline char toupper( char a )
{
return ((a >= 'a' && a <= 'z') ? a-('a'-'A') : a );
}
void main()
{
char ch = toupper( _getch() );
printf( "%c", ch );
}