0

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.

Ryan
  • 1
  • [Cannot reproduce](https://wandbox.org/permlink/wgiBlS9YCSHm4yDV). – Kerrek SB Nov 20 '17 at 00:57
  • You should define the vars in the start of the function. – OmG Nov 20 '17 at 00:58
  • Possible duplicate of https://stackoverflow.com/questions/8474100/where-you-can-and-cannot-declare-new-variables-in-c – isp-zax Nov 20 '17 at 00:58
  • 2
    It will give warning (unused variable) not compile time error(in gcc). Can you post the full code snippet? – Prateek Joshi Nov 20 '17 at 00:58
  • Do you intend to write to the string later? – M.M Nov 20 '17 at 01:01
  • It seems that you have a local vs global variable problem. Can you post a minimum viable example of something that you're trying, but not working? Ie, all the code, including where you declare the variable, and where you try and set it. – roelofs Nov 20 '17 at 01:07

1 Answers1

4

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!

Ed Heal
  • 59,252
  • 17
  • 87
  • 127