Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable declaration in if clause

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.

like image 999
Krushna Avatar asked Apr 08 '13 04:04

Krushna


People also ask

Can I declare variable in IF 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.

Can you declare a variable in an if statement in C?

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.

What is the rule of variable declaration?

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.

What is declaration of variable with example?

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.


1 Answers

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
}
like image 75
Subhrajyoti Majumder Avatar answered Sep 18 '22 06:09

Subhrajyoti Majumder