Monday 4 April 2011

Inline Functions vs Functions


Inline Functions vs Functions

Functions are pieces of code that when called jump to the address of that code and executes. Inline functions on the other hand are pieces of code that are expanded upon calling it, and then it executes the expanded code. Inline functions are faster than functions, but are only to be used if the inline is small. An inline with 100 line of coding wouldn’t be efficient while an inline with 10 lines would be.

To start an inline it has to outside of the main() like a function. You first define the inline function with “inline” followed by the datatype, the name of the inline, and finally the parameters. It should look something like this:

Inline char toUpperCase(char){

}

Now to test it just code inside of your inline, remember to make the code short and simple.

Inline char toUpperCase(char){
     return ((a >= 'a' && a <= 'z') ? a-('a'-'A') : a );
}

So we’re going to test this program, a simple program that converts lowercase characters into upper case characters:

01. #include <stdio.h> 
02. 
03. inline char toupper( char a ) {    
04.     return ((a >= 'a' && a <= 'z') ? a-('a'-'A') : a ); 
05. }
06.  
07. int main() {
08.     printf("Enter a character: ");
09.     char ch = toupper( getc(stdin) );
10.     printf( "%c\n\n", ch );
11. } 
In line 03 we define the inline, and in line 04 it will execute the code to change  lowercase to uppercase. In line 09 is where the inline is called. This is what actually happens:

01. #include <stdio.h> 
02. 
03. inline char toupper( char a ) {    
04.     return ((a >= 'a' && a <= 'z') ? a-('a'-'A') : a ); 
05. }
06.  
07. int main() {
08.     printf("Enter a character: ");
09.     char ch = inline char toupper( getc(stdin) ) {    
10.        return ((a >= 'a' && a <= 'z') ? a-('a'-'A') : a ); 
11.     }
12. }
13.     printf( "%c\n\n", ch );
14. } 

The inline function is expanded here during compile time making the script run faster. Functions are called and go to the address of the function making the program run slower.

*RULE: To make a inline need to use the keyword “INLINE”. Inline functions are only used for small codes, they aren’t meant for huge blocks of code.

The program and help was found at: Microsoft Inline Help




No comments:

Post a Comment