简体   繁体   中英

Space(s) before/after the scope resolution operator

What rule in the C++ language allows spaces to appear before of after the scope resolution operator :: ?

ie the following compiles without a warning :

#include <string>
#include <iostream>

int main ()
{
    std::    string s = "Hello";
    std::    cout << s << std     ::endl;
}

In general, you can put as much space as you like between tokens. In some cases, space is necessary (eg to separate identifiers); in others, it's optional (eg between identifiers and operators).

This is described in C++11 2.7:

Blanks, horizontal and vertical tabs, newlines, formfeeds, and comments (collectively, “white space”), as described below, are ignored except as they serve to separate tokens. [ Note: Some white space is required to separate otherwise adjacent identifiers, keywords, numeric literals, and alternative tokens containing alphabetic characters. end note ]

Syntax rules for the scope resolution operator are as follows:

:: <identifier>
<class-name> :: <identifier>
<namespace> :: <identifier>
<enum class> :: <identifier>
<enum struct> :: <identifier>

In all five cases you can see that the :: operator is used in the same way that other unary and binary operators of C++ are used, which means that the general rules apply to it as well. Namely, you are allowed to have as many whitespace characters between these tokens as you consider necessary.

It will be enough to cite two quotes from the C++ Standard

2.7 Tokens [lex.token] 1 There are five kinds of tokens: identifiers, keywords, literals,18 operators, and other separators. Blanks, horizontal and vertical tabs, newlines, formfeeds, and comments (collectively, “white space”), as described below, are ignored except as they serve to separate tokens.

2.13 Operators and punctuators 1 The lexical representation of C++ programs includes a number of preprocessing tokens which are used in the syntax of the preprocessor or are converted into tokens for operators and punctuators

preprocessing-op-or-punc: one of

::

Each preprocessing-op-or-punc is converted to a single token in translation phase 7::

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM