编译器中的标记数

Number of tokens in compiler

我想知道下面给出的语句中的标记数

a+++b---c

请告诉我代币数量 我跟viva老师说有7个token,他说不对。

你是对的。有七个标记:(在 C 中)

a
++
+
b
--
-
c

根据C标准(pre-C11草案):http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf

6.4 Lexical elements

3 A token is the minimal lexical element of the language in translation phases 7 and 8. The categories of tokens are: keywords, identifiers, constants, string literals, and punctuators. ...

4 If the input stream has been parsed into preprocessing tokens up to a given character, the next preprocessing token is the longest sequence of characters that could constitute a preprocessing token. ... 6 EXAMPLE 2 The program fragment x+++++y is parsed as x ++ ++ + y, which violates a constraint on increment operators, even though the parse x ++ + ++ y might yield a correct expression

6.4.6 Punctuators .. punctuator: one of ++ -- ... + -

因此,https://en.wikipedia.org/wiki/Maximal_munch rule is used as was noted in and comment about a+++b fragment: What does the operation c=a+++b mean? Shahbaz 2011 年 9 月 20 日:“C 和 C++ 的词法分析器,当他们看到某些东西时,尝试匹配最大的字符串。...因此,当词法分析器看到第一个加号,它尝试下一个字符,它看到它可以匹配两个字符作为 ++,然后继续看到下一个 +。因此,解析器看到 a ++ + b

虽然 gcc 和 clang 的代码很复杂,可能会在单个代码示例 () 中混合标准的不同翻译阶段,但我们可能会检查 ++-- 的解析实现.当它看到 char + 时,它可能会根据下一个字符是什么生成不同的标记,如果也是 +,则发出 plusplus 标记,否则发出 plus 标记:

http://code.metager.de/source/xref/llvm/clang/lib/Lex/Lexer.cpp#3264

3264  case '+':
3265    Char = getCharAndSize(CurPtr, SizeTmp);
3266    if (Char == '+') {
3267      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3268      Kind = tok::plusplus;
3269    } else if (Char == '=') {
3270      CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3271      Kind = tok::plusequal;
3272    } else {
3273      Kind = tok::plus;
3274    }
3275    break;

http://code.metager.de/source/xref/gnu/gcc/libcpp/lex.c#2633

2633    case '+':
2634      result->type = CPP_PLUS;
2635      if (*buffer->cur == '+')
2636        buffer->cur++, result->type = CPP_PLUS_PLUS;
2637      else if (*buffer->cur == '=')
2638        buffer->cur++, result->type = CPP_PLUS_EQ;
2639      break;

因此,a+++b---c 表达式的记号是 a ++ + b -- - c. Advisor 可能会说你错了,但只是想让你解释为什么你认为你数到了 7。并且 如果问题 与给定的任务相同并且根据 C 标准解析(或C++ 与此示例的词法相同),您可以解释您的答案并向他展示语言标准的相关部分。