Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign scope to variable in C++

Tags:

c++

gcc

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;
}
like image 336
Nguyen Binh Avatar asked Feb 07 '23 15:02

Nguyen Binh


2 Answers

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.

like image 66
Cheers and hth. - Alf Avatar answered Feb 15 '23 16:02

Cheers and hth. - Alf


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]

like image 25
T33C Avatar answered Feb 15 '23 16:02

T33C