Is c++ a space free language?

2019-07-11 05:48发布

 #define PR ( A, B )  cout << ( A ) << ( B ) << endl ;

- error -> A was not declared in scope
- error -> B was not declared in scope
- error -> expected "," before "cout"

I thought C++ was space free language but when I write above code, then I see some errors. I am still thinking "Is my console is not working properly or library?".

If I am not wrong, how can someone say "C++ is a space free language"?

5条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-11 06:25

You can think of the c++ preprocessor as instruction to the preprocessor (part of the compiler) and not exactly a part of the "c++ space".. So the rules are indeed different although many references are shared between the two 'spaces'..

查看更多
Viruses.
3楼-- · 2019-07-11 06:30

There are numerous exceptions where whitespace matters; this is one of them. With the space after PR, how is the preprocessor supposed to know whether (A,B) is part of the macro expansion, or its arguments? It doesn't, and simply assumes that wherever it sees PR, it should substitute ( A, B ) cout << ( A ) << ( B ) << endl ;.

Another place where whitespace matters is in nested template arguments, e.g.:

std::vector<std::vector<int> >

That final space is mandatory, otherwise the compiler assumes it's the >> operator. (Although I believe this is sorted out in C++0x).

Yet another example is:

a + +b;

The space in between the two + symbols is mandatory, for obvious reasons.

查看更多
Explosion°爆炸
4楼-- · 2019-07-11 06:31

You can't have a space between the macro-function-name and the parenthesis starting the argument list.

#define PR(A, B) cout << ( A ) << ( B ) << endl

Whitespace in the form of the newline also matters, because a #define statement ends when the preprocessor hits the newline.

Note that its usually a bad idea to put semicolons at the end of macro function definitions, it makes them look confusing when used without a semicolon below.

查看更多
放我归山
5楼-- · 2019-07-11 06:48

A #define is not c++, it's preprocessor. The rules of c++ aren't the same as the rules of the preprocessor.

To indicate a macro, you mustn't have a space between the name and the parenthesis.

#define PR(A, B)  cout << ( A ) << ( B ) << endl;
查看更多
孤傲高冷的网名
6楼-- · 2019-07-11 06:51

You're asking for defense of a claim I've never heard anyone bother to voice...?

The preprocessor stage doesn't follow the same rules as the later lexing etc. stages. There are other quirks: the need for a space between > closing templates, newline-delimited comments, string literals can't embed actual newlines (as distinct from escape sequences for them), space inside character and string literals affects them....

Still, there's a lot of freedom to indent and line-delimit the code in different ways, unlike in say Python.

查看更多
登录 后发表回答