Ryan
Ryan

Reputation: 1

Won't let me declare a string in an if statement C

I'm trying to set a string to be different things depending on an int, but when I declare a string in any if statement, even an always true one it seems to give me error: 'correctColor' undeclared (first use in this function).

If I have this line by itself, my code works fine.

    char correctColor[] = "red";

But if I have something like

bool test = true;
if(test){
char correctColor[] = "red";
}

it gives me the error above. Any help is greatly appreciated.

Upvotes: 0

Views: 86

Answers (1)

Ed Heal
Ed Heal

Reputation: 60007

Please see the comments below

   bool test = true;
   if(test){
     char correctColor[] = "red";
     // correctColor is available here until the end brace
   }

   // correctColor is not available here - it is now out of scope

Consider if test is false - Then correctColor would not be declared!

Upvotes: 4

Related Questions