Search code examples
c++c-preprocessorpreprocessor-directive

Overriding "endl" in C++ by #define preprocessor directive


I used the following code to override and replace endl with something other than "a new line".

#include <iostream>
#include <string>
using namespace std;

#define endl "OOOO"  //replacing "endl"


int main(){

    cout << "start " << endl << " end";
    return 0;

}

Then the result will be:

start OOOO end

instead of:

start
end

But doing the same to cout causes errors.

Why can we do this to endl but we cannot do the same to cout?


Solution

  • It of course depends upon what you define your macro as, and how you use it. After preprocessing, this:

    #define endl "OOOO"
    cout << "start " << endl << " end";
    

    becomes this:

    cout << "start " << "OOOO" << " end";
    

    Which is a perfectly valid statement. However, after preprocessing this:

    #define cout "OOOO"
    cout << "start " << endl << " end";
    

    becomes this:

    "OOOO" << "start " << endl << " end";
    

    Which is not a valid statement. If you do this though:

    #define printf "OOOO"
    cout << printf;
    

    That becomes this:

    cout << "OOOO";
    

    Which is fine. Likewise, if you did this:

    #define cout "OOOO"
    printf(cout);
    

    it becomes this:

    printf("OOOO");
    

    Which is also fine.