Assign scope to variables in C ++

Take a look at this code, can someone explain to me why it is a+1;assigned b?

#include <iostream>

int main(int argc, char *argv[])
{
  int a = 5;

  int b = ({
      std::cout << "inside scope" << std::endl;
      a+1;
  });

  std::cout << "b value: " << b;
}
+4
source share
2 answers

Design

int b = ({
    std::cout << "inside scope" << std::endl;
    a+1;
    });

& hellip; not standard C ++, but a language extension provided by the g ++ compiler.

It is called the operator expression " and essentially allows you to enter local variables for calculation.

Since you are not using this, you could simply use the standard C ++ comma expression as follows:

int b = (
    std::cout << "not inside scope" << std::endl,
    a+1
    );

In both cases, the expressions in the sequence are evaluated in order, and the value of the expression as a whole is the value of the last evaluation.


, , , , ++:

int b = [&](){
    double bah = 3.14;
    std::cout << "inside scope" << std::endl;
    return a+!!bah;
    }();

++ 17 std::invoke, , JavaScript'ish () , invoke .

+7

- ,

b = a + 1 = 5 + 1 = 6

, .

GCC, , , . GCC :

warning: ISO C++ forbids braced-groups within expressions [-Wpedantic]

+1

All Articles