Jignesh
Jignesh

Reputation: 565

Behaviour of #define macro expansion in C++

I knew that if we don't put space after closing angle brackets in a variable declaration, C++ throws the following error.

‘>>’ should be ‘> >’ within a nested template argument list

But the error doesn't come if I use #define like in this code. Can someone explain me this?

I think #define is just a macro expansion and works like find-replace, so both the ways of declaring variable here should be identical.

Also this error doesn't occur if I compile it with C++11.

#include <bits/stdc++.h>
using namespace std;

#define vi vector<int>

int main(){
    //Doesn't work, compile error
    vector<vector<int>> v;

    //Works
    vector<vi> vv;
}

Upvotes: 29

Views: 3591

Answers (1)

Mike Seymour
Mike Seymour

Reputation: 254471

Macro expansion happens after tokenisation; it doesn't replace text, but sequences of tokens.

This means that, with the macro, the expansion of vi gives a > token, separate from the one following the macro invocation. In each case, tokenisation only finds a single > character, so that's the resulting token.

Without a macro, the "greedy" tokenisation rule meant that the two consecutive characters were treated as a single >> token, until C++11 added a special rule for this case.

Upvotes: 36

Related Questions