Nguyen Binh
Nguyen Binh

Reputation: 355

Assign scope to variable in C++

Have a look at this code, can someone explain me why a+1; is assigned to 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;
}

Upvotes: 4

Views: 396

Answers (2)

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145204

The construct

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

… is not standard C++, but a language extension provided by the g++ compiler.

It's called “statement expression”, and essentially allows you to introduce local variables for a computation.

Since you don't use that, you could just have used a standard C++ “comma expression” like this:

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.


Where you absolutely need to introduce variables, or e.g. a loop, for the computation in an initializer, you can do that with a standard C++ lambda:

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

In C++17 and later you can use std::invoke to make such code more clear, without the JavaScript'ish () invocation at the end but instead the word invoke up front.

Upvotes: 7

T33C
T33C

Reputation: 4429

The value of the scope is the last statement within the scope, so in this case

b = a + 1 = 5 + 1 = 6

I don't advise writing code like, it is not very clear.

It is a GCC extension called a statement expression so another good reason not to use it because it is not portable. GCC returns a warning:

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

Upvotes: 1

Related Questions