if(someCondition)
int a=10;//Compilation Error
else if(SomeOtherCondition){
int b=10;//no compilation Error
}
Why this happening.Why there is compilation error in first case. If i put braces then no compilation error but for if statement braces are optional if it's one statement.
Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared.
No. That is not allowed in C. According to the ANSI C Grammar, the grammar for the if statement is IF '(' expression ')' statement . expression cannot resolve to declaration , so there is no way to put a declaration in an if statement like in your example.
Rules for defining variablesA variable can have alphabets, digits, and underscore. A variable name can start with the alphabet, and underscore only. It can't start with a digit. No whitespace is allowed within the variable name. A variable name must not be any reserved word or keyword, e.g. int, goto, etc.
Declaration of a variable in a computer programming language is a statement used to specify the variable name and its data type. Declaration tells the compiler about the existence of an entity in the program and its location. When you declare a variable, you should also initialize it.
You need to define scope of the int a
in if statement
and it will be defined with curly braces {}
.
if(someCondition){
int a=10; // works fine
}else if(SomeOtherCondition){
int b=10; //works fine
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With