Tom Waits
Tom Waits

Reputation: 135

Newbie C++ Questions - Why doesn't this if statement execute?

I have been trying to solve a problem on Codewars and ran into a problem with an if statement executing. If I test the following code, I get the error: "error: use of undeclared identifier 'out'", but if I use the conditional operator instead (see the commented line) everything works fine! I'm probably missing something obvious but could somebody point out why this is?

#include<cmath>
using namespace std;
class Suite2
{
    public:
      static string game(unsigned long long n){
      
      ostringstream os1, os2;
      os1 << pow(n,2)/2;
      os2 << pow(n,2);
      
      if(n%2==0){
        std::string out = "[" + os1.str() + "]";
      }
      else{
        std::string out = "[" + os2.str() + ", " + "2]";
      }
      
      //return (n%2==0) ? "[" + os1.str() + "]" : "[" + os2.str() + ", " + "2]";
      return out;
    }
};

Upvotes: 0

Views: 104

Answers (2)

Adrian Mole
Adrian Mole

Reputation: 51894

Your declarations (there are two of them) of the out variables are inside the scope of the if and else blocks; as such, they can't be accessed outside those scopes.

You need to define the variable outside those scopes and then assign values to them in the relevant block:

class Suite2 {
public:
    static string game(unsigned long long n)
    {

        ostringstream os1, os2;
        os1 << pow(n, 2) / 2;
        os2 << pow(n, 2);

        std::string out; // Declare the "out" variable here...
        if (n % 2 == 0) {
            out = "[" + os1.str() + "]"; // ... and assign it a value here...
        }
        else {
            out = "[" + os2.str() + ", " + "2]"; // ... or here.
        }

        return out;
    }
};

Upvotes: 3

Hatted Rooster
Hatted Rooster

Reputation: 36513

The if statement executes alright, but you're introducing a local scope in which you declare and initialize out so the outer scope doesn't have access to out.

Move it up a scope so it's level with the return then assign and it'll work:

static std::string game(unsigned long long n) {
      
      ostringstream os1, os2;
      os1 << pow(n,2)/2;
      os2 << pow(n,2);
      
      std::string out = "";
      if(n % 2 == 0) {
        out = "[" + os1.str() + "]";
      }
      else {
        out = "[" + os2.str() + ", " + "2]";
      }
      return out;
    }

Side note: Stop using namespace std; and add #include <string>.

Upvotes: 2

Related Questions