Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one declare a variable inside an if () statement? [duplicate]

Tags:

Possible Duplicate:
Declaring and initializing a variable in a Conditional or Control statement in C++

Instead of this...

int value = get_value(); if ( value > 100 ) {     // Do something with value. } 

... is it possible to reduce the scope of value to only where it is needed:

if ( int value = get_value() > 100 ) {     // Obviously this doesn't work. get_value() > 100 returns true,     // which is implicitly converted to 1 and assigned to value. } 
like image 962
x-x Avatar asked Jan 31 '13 07:01

x-x


People also ask

How do you declare a variable in an if statement?

If you're new to the syntax that's used in the code sample, if (int i = 5) { is a perfectly valid way of declaring and defining a variable, then using it inside the given if statement. It allows us to write terser, clearer code, while also avoiding limiting the scope of a variable.

Can you assign a variable inside an if statement?

Yes, you can assign the value of variable inside if.

How declare variable in if condition in C#?

C# has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.

Can we declare a variable in if statement in Java?

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. This region of the program text where the variable is valid is called its scope .


1 Answers

If you want specific scope for value, you can introduce a scope block.

#include <iostream>  int get_value() {     return 101; }  int main() {     {         int value = get_value();         if(value > 100)             std::cout << "Hey!";     } //value out of scope } 
like image 183
Rapptz Avatar answered Oct 19 '22 23:10

Rapptz