+ 1

Declaration in loops and conditional statements

So I tried to declare a string type variable in an "if" conditional statement and gave it me an error. int x = 1 if(x>0) { string msg = "Hi"; console.writeline(msg); } the correct format is this: int x = 1 string msg if(x>0) { msg = "Hi" console.writeline(msg); } This may not be a crucial question but I was just wondering why can't I declare the string inside the "if" statement. for "x" maybe different since its a part of the syntax, but whats the difference for "string msg"?

18th Mar 2017, 4:02 PM
Amir Hossein Karimi
Amir Hossein Karimi - avatar
4 Respostas
+ 14
This compiler prevents you from having declarations inside conditional statements because if the conditional statement isn't executed, the variable wouldn't exist - the compiler has no idea if you plan on using the variable further in your code, which would cause implicit errors.
18th Mar 2017, 4:20 PM
Hatsy Rei
Hatsy Rei - avatar
+ 1
You can't declare variables inside of an IF statement. IF checks the value inside its scope "()". If the value is TRUE it will proceed with the code inside the brackets. Anyway your code has alot of errors. Don't forget to end each line with ";" and make sure you have the right syntax, like -> Console.WriteLine
18th Mar 2017, 4:25 PM
Леон Яровинский
Леон Яровинский - avatar
0
error: embedded statement cannot be declaration or labeled statement... some error message like this...
18th Mar 2017, 4:12 PM
Amir Hossein Karimi
Amir Hossein Karimi - avatar
0
would not... exist....😲 gosh your a genius. Thank you.
18th Mar 2017, 4:24 PM
Amir Hossein Karimi
Amir Hossein Karimi - avatar