Click here to Skip to main content
15,896,153 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have tried to declare a variable inside the if statement but it says the the variable is not declared in the scope

What I have tried:

C++
#include<iostream>

using namespace std;
int main()
{
double y;
cout<<"enter y: ";

cin>>y;

if (x>10)
{
double x=y*15;
cout<<x;
return 0;
}
Posted
Updated 27-Sep-18 5:53am
v2
Comments
jeron1 27-Sep-18 11:15am    
x is being used in the if statement itself, before it's declared, perhaps that should be if (y > 10)?
Richard MacCutchan 27-Sep-18 11:33am    
Yes but it must be defined before it can be used.

Yes it is ok in C++, but your x is declared later!!!

But it in your code it makes little sense.
 
Share this answer
 
v2
Yes it's fine - you can declare a variable within any set of curly brackets, and it has it's advantages, because the variable goes out of scope at the closing bracket. And when it goes out of scope, it cannot be referenced.

So if for example you had a pointer which you allocated memory, used it and then deallocated it, declaring it at the top of the if and deallocating the memory at the bottom means that you cannot accidently use the deallocated pointer outside the block.

Your example is pretty trivial, but yes, it's allowed, and often a good idea!
 
Share this answer
 
Yes, but that will not work in your case. if block itself is a scope, and you define a scope and the variables are only accessible inside the scope, not outside, and not at the boundary either.

So, I think something you would want to do would be,
C++
cin >> y;

if (y > 10)
{
   double x = y * 15;

This would work, and will test if the value of y is greater. Why I think this would be the right approach? Because, you just took input in the y variable, and you would now need to test if the input from user was more than 10.

Otherwise, you can do this,
C++
cin >> y;

double x = 0; // Initialized with 0, to avoid garbage, and to make my next sentence true
if (x > 10)
{
    // x has been already defined
    x = y * 15;

But notice, that now your if block would never execute, because it won't be more than 10 and thus if block would never executed.

Scope - cppreference.com[^]
 
Share this answer
 
Sure. Just don't expect to be able to use that variable outside the if block.

What you're looking at is "scope". This is the concept is visibility for variables and methods. Read up on it here: Variable and Method Scope in Microsoft .NET[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900