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. }
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.
Yes, you can assign the value of variable inside if.
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.
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 .
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 }
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