Preprocessor Solution

  • + 9 comments

    inline makes defined function as a copy-paste code, i.e. it suggest to compiler that "You can replace this code, instead of calling it as a function.". Let me explain with an example. We code this program:

    #include <iostream>
    
    inline void print(string name) {
        std::cout << name << endl;
    }
    
    int main() {
       string myName = "Meysam";
       
       print(myName);
       
       return 0;
    }
    

    When you compile this code, your code suggest to your compiler that "It's a good idea if you replace print function with it's code, huum?" and based on situation, if compiler accepts this suggestion, code will converts to this:

    #include <iostream>
    
    inline void print(string name) {
        std::cout << name << endl;
    }
    
    int main() {
       string myName = "Meysam";
       
       std::cout << myName << endl;
       
       return 0;
    }
    

    and then compiled.

    This optimision feature of C++ in many situations is a good solution instead of using macros. It will reduce overhead of program, but this also has some disadvantures that you can find them with search on google :D.

    If any explaination is required, I'm here ;).