Are variables declared in loops visible to rest of the code? [duplicate] - c++

This question already has answers here:
What is the scope of a 'while' and 'for' loop?
(10 answers)
Closed 9 years ago.
I was reading this book and it said :
Variables declared in a scope aren't visible outside it.
It also said :
Scopes are declared by 2 curly braces - like a block of code.
So, if I had a situation like this :
for(_statement1_)
{
int var;
/*code*/
}
cout << var << " number of rockets left.\n";
Would the value printed be the same as the value of the var declared in the loop?
Thank you

As your book says, the variable is scoped inside the loop's block, and isn't visible outside it.
Your code won't compile unless there is a different variable var outside the loop's scope. If there is, then the final statement would use that, not the one in the loop which is now out of scope.

No, you can not use that variable outside the loop. var is visible only inside the loop.

It will be a compiler error since the scope of var limited inside for loop only.

Related

Usage of enum - global and local [duplicate]

This question already has an answer here:
How to access a global variable within a local scope?
(1 answer)
Closed 6 years ago.
I just tried it to use globaly defined enum with same name as locally defined.
I had initiallized with same values except the start point.
enum Day {Sunday = 1 ,Monday,Tuesday,Wednesday,Thursday,Friday /*= 15 */,Saturday};
void enumUse() {
enum Day {Sunday = 2 ,Monday,Tuesday,Wednesday,Thursday,Friday /*= 15 */,Saturday};
Day today = Tuesday;
cout<<Sunday<<endl;
cout<<Monday<<endl;
cout<<Tuesday<<endl;
cout<<Wednesday<<endl;
cout<<Thursday<<endl;
cout<<Friday<<endl;
cout<<Saturday<<endl;
cout<<"Today: "<<today;
cout<<endl;
}
This code snippet gives the output of local enum.
If comment it out, it gives output related to global one.
How could I use global enum without commenting local enum.
You can use the scope resolution operator, because the global Day is defined in global scope
//'Day' from global scope
::Day today = ::Tuesday; //'Tuesday' also needs it because it would take the local one,
//which can't be assigned to the global 'Day' (they're different
//enums after all)

Why the variables defined inside a for loop only exist inside of it?

I was reading C++ Primer by Stanley B. Lippman and at the part of flow control it shows an example of a for-loop like this one:
#include <iostream>
int main(void){
int sum=0;
for (int val=1; val <= 10; val++)
sum +=val;
std::cout << sum << std::endl;
return 0;
}
If I try std::cout << val; outside of the for-loop, the IDE gives me an error. But I want to understand why it happens and how it is different from this code:
#include <iostream>
int main(void){
int sum=0;
int val;
for ( val=1; val <= 10; val++)
sum +=val;
std::cout << sum << std::endl;
std::cout << val;
return 0;
}
Where I can actually print the val value without any problem.
Does it have something to do with local variable considering the for-loop a function that we are using inside of the main?
Every variable has scope, which is (loosely speaking) its lifetime.
A variable declared in the head of a for loop has scope limited to the for loop. When control passes out of the loop, the variable passes out of scope. Exactly the same thing happens to variables declared in a function, when control passes out of the function.
Does it have something to do with local variable considering the for-loop a function that we are using inside of the main?
Nothing to do with functions; there are plenty of other ways to get a scope, including a block:
int main()
{
{
int x = 0;
}
std::cout << x; // error
}
And a for loop is another example.
Its deliberate. Its called scope, Whenever you introduce a block { /*stuff here */ } (and a few other places) the variables inside the block are local to the block and supersede (hide) variables of the same name defined outside the block. It helps to ensure block-local code does not tread on other variables. Can be useful when editing an old codebase and you don't want to accidentally use a wider scoped variable.
The concept behind this is called Scope of the variable. Whenever a variable is created a memory location is assigned to it. So in order to optimize the memory usage scope of the variable is defined.
In the first case, the variable is limited only to the for loop. The variable is created inside at the beginning of the loop, utilized inside the loop and destroyed when the execution comes out of the loop.
In second case, the variable is created outside the loop so it persists till the execution of the program and hence you were able to access it even after the loop.
The variable declared inside the for loop is an example of local variable and that declared outside is an example of global variables.
Not only with the loops, the local variables will also be used in if..else blocks, functions and their usage is limited only within the scope.
Hope this answers your question.
Running this exact code does not turn up any errors for me. I get a value of 55 for sum and 11 for val as expected. Because you defined val outside of your for loop but in main, it should be good everywhere within the main() function to the best of my knowledge. As a general rule, if you declare a variable in between two curly braces without any fancy keywords, it should stay valid within those two curly braces (being "local" to that block of code). I am no c++ guru, so there might be exceptions to that (I am also not sure if "if" statements count as code blocks whose locally defined variables only work within the statement).

Why is this C++ code WORKING when it SHOULDN'T?

I am learning C++ using Robert Lafore's book ( OOP with C++ ).
In the book, I have encountered this example:
#include <iostream>
#include <conio.h>
using namespace std;
void main ()
{
int numb;
for ( numb = 1 ; numb <= 10 ; numb++ )
{
cout << setw(4) << numb;
int cube = numb*numb*numb;
cout << setw(6) << cube << endl;
}
getch();
}
The variable 'cube' has been declared as int 'inside the loop body'.
int cube = numb*numb*numb;
Since the loop iterates 10 times, the variable 'cube' will also get declared 10 times. 'cube' is accessible inside the loop body no matter what iteration. So, when we enter the loop body for, say, 2nd iteration, 'cube' is already known( because it already got declared during the 1st iteration), and another declaration for 'cube' should give an error of "redefinition". But instead, it builds successfully and debugs without a problem. Why?
The scope of an automatic variable (such as cube) is the block in which it is declared. The block that cube is declared in is the body of the for loop. At the end of each iteration, the cube variable goes out of scope, the next iteration starts and then cube is introduced to the scope again. Logically, there is no clash because no two identifiers cube exist in the same scope - in fact, there is only a single declaration of cube.
It might be worth distinguishing between the declaration of a variable and the creation of an object due to that declaration. There is only one declaration int cube = ...;. It doesn't matter that this piece of code may be reached many times; it's still only one declaration. The rules of the language say that you cannot declare two variables with the same name in the same scope, but that's okay since you're only declaring it once. This is a completely static rule that your compiler is able to analyse.
It just so happens that your declaration is reached 10 times because of your for loop, which means that 10 int objects will be created. Due to the scope of the variable, they won't all exist at the same time. This is not a static property of the program. The compiler cannot in general know beforehand how many times a line of code will be reached.
When you enter the loop a 2nd time, the first cube has gone out of scope so it's all OK.
Two cubes in the same scope would be a problem:
{
int cube = 0;
int cube = 1;
}
You've discovered "Automatic-storage duration".
The variable cube is declared inside the loop. Especially, inside the block-scope of the loop. At the end of the loop, this variable will be destroyed, just like any variable declared in any block-scope, be it a function, a loop, an if/else block, or just a raw block scope that you can declare anywhere in the code using { and }, i.e.:
int main(){
//Beginning of block
{
int cube = 1;
//cube exists and is declared here
}//End of block
//cube is gone here
return 0;
}
So in fact, every iteration of the loop will have its brand new and fresh cube variable.
The variable cube is only used inside the body of the for loop. I am not sure that saying it is declared ten times is correct (a declaration, actually a definition in your case, is a syntactic and static textual portion of source code).
In C++ you can (and you often do) have blocks with local variables. The scope of cube starts at it declaration and ends at the end of the containing block (braces { ... }).
If the type of a defined variable has a constructor, it is called at the definition point. If that type has a destructor, it is called conceptually at the end of the block (figuratively, just before the closing } ....).
The variable will be declared in each iteration of the loop, and then it will go out of scope as the block ({...}) ends, i.e. it will cease to exist. Then on the next iteration it will be declared again, which is not a redeclaration, since it didn't exist. It is said to be a "local variable", in this case local to the block.
As cube is defined inside the cycle body its scope will be that body. So after each iteration completes cube will go out of scope and on the next iteration a brand new cube will be created. This is what happens in theory. It may happen though that the compiler optimizes this code and only ever creates one variable. Either way the code is perfectly valid and will work as excepted.
The variable 'cube' is declared and defined in each iteration. The scope of 'cube' dies with the iteration and new declaration and definition in each loop happens.

Is this code valid C++?

Is the following code valid C++?
const int var = 10;
{
int var[var]; // why doesn't this give any error ?
}
Note : The code compiles on my g++ compiler.
As-is? No. If it were in the body of a function? Yes.
The first line declares an integer constant named var with a value of 10.
The braces begins a new block. Within that block, a new variable is declared, named var, which is an array of int with a size equal to the value of the integer constant previously declared as var (10).
The key is that var refers to the first variable until after the second variable named var is fully declared. Between the semicolon following the second declaration and the closing brace, var refers to the second variable. (If there was an initializer for the second variable, var would begin to refer to the second variable immediately before the initializer.)
Yes the code is valid C++. Non-local var is visible up to the point of declaration of local var.
So int var[var] defines a local array of 10 integers.
Yes the code is valid C++
It is a concept of SCOPE : Hiding Names
const int var = 10;
{
int var[var]; // why doesn't this give any error ?
}
I think this link clears your doubt
IN C++:
http://msdn.microsoft.com/en-US/library/9a9h7328%28v=VS.80%29.aspx
In C :
http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fzexscope_c.htm
If u want deep knowledge On this : Go for this link,here the information is about Lexical versus dynamic scoping
http://en.wikipedia.org/wiki/Scope_%28programming%29
but in your code : "Scope ::" of visibility of var .Here It differs like local and non-local variable.
Inside braces { x=1; } local variable . where as here {y=1;{x=1;}} ,here it differs.
helpful links
http://msdn.microsoft.com/en-us/library/b7kfh662%28VS.80%29.aspx
http://www.awitness.org/delphi_pascal_tutorial/c++_delphi/c++_scope_variables.html

Why does using the same count variable name in nested FOR loops work?

Why does the following not give an error?
for (int i=0; i<10; ++i) // outer loop
{
for (int i=0; i<10;++i) // inner loop
{
//...do something
}
//...do something else
}
The way I understand it, variables in braces ({...}) are in scope only within these braces. But the inner loop is inside the braces of the outer loop. So as soon as I declare int i=0 for the inner loop, shouldn't I get an error about multiple definitions?
You are actually making a new variable with the same name as another variable. Since they are in different scopes this is allowed, and the variable in the inner scope "owns" the name. You will not be able to access the outer-scoped i inside the inner scope.
The for loop declaration itself is part of the scope of the for loop, so counts as part of the inner-scope in the case of the second i.
The C++ compiler accepts this as valid, as the scope of the second is only within the { } braces. If you implement the same in C, you will see an error like this:
$ gcc test.c
test.c: In function ‘main’:
test.c:10: error: ‘for’ loop initial declaration used outside C99 mode
test.c:12: error: ‘for’ loop initial declaration used outside C99 mode
This is illegal in most C dialects; it is a legal C++ declaration, and so may be accepted if you are compiling C with a C++ compiler:
for( int i=0; i<5; ++i){}
It is common to have a loop iterator only in the scope of the loop in C++, but C makes sure (specially with the C90, not C99), that the declaration is outside the scope of the loop. Hope that helps ... :-)
So, when you declare another FOR loop within the older one, then the scope start fresh and your code compiles without any error in C++ or C99. This is the usual accepted norm for a scope declaration.
The best way to understand this is to think about everything between the ( and ) when you declare a for loop as being inside the braces of that for loop, at least as it relates to the scope.
To understand this, consider a function in which you have no x variable declared, then the following code inside will give you an error. (We are also assuming that you have no other x variable defined globally.)
for (int x = 0; x < 10; x++)
{
something();
}
x++; // error, x is not defined.
The inner loop starts another level of scoping, for loops start the scope in the loop definition so the second i is in a new scope.
see
http://en.wikibooks.org/wiki/C%2B%2B_Programming/Scope#Scope_using_other_control_structures
ARE YOU SURE YOU DON'T GET AN ERROR WHILE EXECUTING THIS ....?
you are trying to define the two int variable within the same boundary .due to this this will generate the error . in c# if u try out the same code you will get the error
Error 1 A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'parent or current' scope to denote something else