Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of #define macro expansion in C++

Tags:

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; } 
like image 780
Jignesh Avatar asked Feb 17 '15 10:02

Jignesh


People also ask

What is behaviour and examples?

The definition of behavior is the way a person or thing acts or reacts. A child throwing a tantrum is an example of bad behavior. The actions of chimps studied by scientists are an example of behaviors.

What is behaviour word?

1. Behavior, conduct, deportment, comportment refer to one's actions before or toward others, especially on a particular occasion. Behavior refers to actions usually measured by commonly accepted standards: His behavior at the party was childish.

What is the meaning of behavior of a person?

Human behavior is the potential and expressed capacity (mentally, physically, and socially) of human individuals or groups to respond to internal and external stimuli throughout their life. Behavior is driven by genetic and environmental factors that affect an individual.

What are the 4 types of behavior?

A study on human behavior has revealed that 90% of the population can be classified into four basic personality types: Optimistic, Pessimistic, Trusting and Envious.


1 Answers

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.

like image 96
Mike Seymour Avatar answered Sep 21 '22 21:09

Mike Seymour