0

I am a newbie in C++ and it is a very easy task but all tutorials that I looked use cout some string in if-else conditions.

I want to update a global variable in if-else statement.

Here is the code;

        double theta_radian{};
        if (l2 >= l1)
        {
            double theta_radian = atan2(e2.y(), e2.x());
            std::cout << "theta_local" << theta_radian << std::endl;
            
        }
        else
        {
            double theta_radian = atan2(e1.y(), e1.x());
            
        }
        std::cout << "theta_radian" << theta_radian << std::endl;

I want to update theta_radian variable based on the if-else condition.

I don't want to create a vector and push_back to it since it is a simple practice and I want to learn how to do it properly.

Thanks in advance!

Tyr
  • 580
  • 4
  • 26
  • 2
    Just remove the `double` before `theta_radian` in the `if` and `else` blocks. That declares new variables, local to the scope of each block. – Adrian Mole May 01 '21 at 10:52
  • 2
    `theta_radian` is still a local variable, not a global one, even though it's shadowed by another local variable of the same name. A global variable would be a variable defined at namespace scope, not inside a function or type. – fabian May 01 '21 at 11:02

1 Answers1

-1

Here is the updated code:

double theta_radian; // NOTE: Brackets were not needed here, also 'double' is a value-type
if (l2 >= l1)
{
    theta_radian = atan2(e2.y(), e2.x());
    std::cout << "theta_local" << theta_radian << std::endl;
}
else
{
    theta_radian = atan2(e1.y(), e1.x());
}
std::cout << "theta_radian" << theta_radian << std::endl;

All you had to do was removing the "double" qualifier in following definitions. Note that "theta_radian" will be local to the function (or scope, had it been defined solely under the 'if/else' clause').

As a next step, I would recommend reading about stack-based vs heap-based definitions, pointers and then continue with "shared_ptr".

  • Why two "std::cout"? – Dominique May 01 '21 at 11:02
  • @Dominique it was from my code just to compare results, apperantly deleting 'double' works. – Tyr May 01 '21 at 11:05
  • How is the *"As a next step ..."* part related to the question? Also why recommending `shared_ptr` without even mentioning `unique_ptr` will likely advocate for sharing ownership even in cases where transfering the ownership would be preferrable. – fabian May 01 '21 at 11:07