简体   繁体   English

在({…})中使用什么C ++ 11标准规则来确定表达式的类型

[英]What rules of C++11 standard are used to determine the type of the expression in ({ … })

I hasn't understand what compiler does here and why it's working c++ code 我不明白什么是编译器在这里做什么,以及为什么它能正常工作的C ++代码

#include <cstdio>
int main()
{
    printf( ({  // (1)
                struct some_noize_struct {
                   // there may be another code
                };
                42;
                "abc";
              }) // (2)
            );

    return 0;
}

Type of expression between (1) and (2) braces is const char*. 大括号(1)和(2)之间的表达式类型为const char *。 After some experimens i unrerstood that type of (1)-(2)-expression determined by last part. 经过一些实验,我理解了由最后一部分确定的(1)-(2)-表达式类型。

Here is a sample code. 这是示例代码。 It works on c++11 and later. 它适用于c ++ 11及更高版本。 http://cpp.sh/5tb47 http://cpp.sh/5tb47

My question: how it works. 我的问题是:它是如何工作的。

As @HolyBlackCat explains, the code you listed uses a GCC compiler extension to C++ (and to C), while allows for compounds statements to be used as expressions. 正如@HolyBlackCat解释的那样,您列出的代码使用了GCC编译器对C ++(和C)的扩展,同时允许将compounds语句用作表达式。

In your printf() statement, you need to provide a const char* or const char* & expression as the first argument to the function, eg printf("hello") or printf(getenv("PATH")) . 在您的printf()语句中,您需要提供const char*const char* &表达式作为该函数的第一个参数,例如printf("hello")printf(getenv("PATH")) The extension allows the interpretation of a curly-braced block as such an expression, using the last statement in the block. 该扩展允许使用大括号中的块中的最后一条语句将其解释为此类表达式。 The block in your case is: 您的情况下的障碍是:

{ 
    struct some_noize_struct { 42 };
    42;
    "abc";
}

which has 3 statements. 其中有3条陈述。 The last statement is the value of the entire expression, which means that what the printf() sees is essentially the same as if you had typed printf("abc") . 最后一条语句是整个表达式的值,这意味着printf()看到的内容与您键入printf("abc")基本上相同。

This kind of code is not standard C++ (C++11 or any another version), nor is it standard C . 这种代码不是标准的C ++(C ++ 11或任何其他版本),也不是标准的C。

I suggest you write the maintainers of the "C++ Shell" website and ask them to display the exact compilation command-line they use, and/or make sure they use --std=c++11 to compile C++11 code - which it looks like they aren't doing. 我建议您编写“ C ++ Shell”网站的维护者,并要求他们显示其使用的确切编译命令行,和/或确保他们使用--std=c++11来编译C ++ 11代码-看起来他们没有这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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