Is this code valid C++? - 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

Related

How to keep the value of a string?

Hey guys I have a question about variables and If statements.
The reason I am asking is I am assigning tokens in a vector of strings to variables but if my vector only has 3 elements and I try to assign a variable to myVector(5) I get an error.
This is my solution to that problem
std::string element5;
if(myVector.size () >= 4)
(
std::string element5 = myVector.at(4)
}
But that wont change the string outside the if statement? My code works fine if I have exactly 5 elements and no error check but if I'm passing in standard input I wont really know how many elements there are all I will know is that there are a max of 50 elements.
I dont need to ouput any elements just run this code on each one
if(countSubstring(element5,"a") > 0)
{
a = a + 1
}
then I would output a.
how do I make element5 keep its new string?
Problem
Your code here redefines your variable element5:
std::string element5;
if(myVector.size () >= 4)
(
std::string element5 = myVector.at(4)
}
Here you first declare element5 after the first line, and then you re-declare it at the third line in your if statement. That essentially "recreates" the variable element5 for that scope {}. And then of course is poped right after the scope. So you won't see a change in element5 if you try to print it out of the scope.
Solution
Easy, just don't re-declare your variable, and you're all set! Like so:
std::string element5;
if(myVector.size () >= 4)
(
element5 = myVector.at(4)
}
Why is this happening?
Like I said, down in the assembly level the variable gets pushed, and then suddenly when it comes down to another level and the same variable gets re-declared, the global variable gets forgotten about. And as soon as the scope ends:
{
//This is a scope
}
the re-declared variable gets poped off the stack, and we have our original element5 back! This will leave element5 in the same position since you didn't actually change it ;).
Undefined Behaviors(UB)
Don't reference to an out-of-scope object; don't do it!
C++: Reference to "out of scope" object
References
What happens when C++ reference leaves it's scope?
What happens in C++ when I pass an object by reference and it goes out of scope?
Glossary
scope: The "container" a program is currently executing under; for example, let's take this:
int main() {
//1st scope
if (true) {
//2nd scope
{
//third scope
}
}
}
Undefined Behavior(UB):
When in an undefined/unknown state at any time given during the compilation. Compiler does whatever it decides to do, making it a very dangerous Behavior especially if you are writing a big project! Here is a good question/answer to this topic:
https://softwareengineering.stackexchange.com/questions/99692/philosophy-behind-undefined-behavior
You are redefining the string inside the if statement, you shouldn't do that because you want to use the string that has been declared before.
So just replace std::string element5 = myVector.at(4) with element5 = myVector.at(4)

Uninitialized variable - passing it to a function

http://en.cppreference.com/w/cpp/language/storage_duration
Static local variables
Static variables declared at block scope are initialized the first
time control passes through their declaration (unless their
initialization is zero- or constant-initialization, which can be
performed before the block is first entered). On all further calls,
the declaration is skipped.
What is the meaning of 'static' in this quote? Is it:
static storage duration. The storage for the object is allocated when
the program begins and deallocated when the program ends.
If so, then it doesn't explain what happens to int k; in the main or any other function in terms of initialization, because k is not a static variable (it doesn't get allocated when the program begins and deallocated when the program ends - wait a second, you might say that the main function starts running when the program begins and returns when the program ends, but that's not how it works I guess).
In the main function:
int k;
k++;
results in an error: uninitialized local variable 'k' used.
So if k above is not a static local variable, could you give an example of such variables?
And could anyone tell me why the following code compiles and runs without any issues, even though k is not initialized?
Given a function with no body:
void foo(int* number) { }
And calling it like this in main:
int k;
foo(&k);
k++;
It now compiles and runs with no problems, but the value of k is -858993459. The compiler didn't like the fact I attempted to increment it without initiation, but passing it to foo caused that the compiler forgot about it. Why?
Probably depends on your compiler implementation.
I guess the compiler sees that you variable is passed to a function in a non-const way, so the function can potentially modify/initialize the value of k.
Your compiler doesn't dig into the function to extrapolate the logic, so it let you compile the code.
EDIT : I don't get the same behaviour with this online compier : http://cpp.sh/9axqz
But the compilation warning disapears as soon as I do something with the number in the function.
A static local variable is something like this:
void example() {
static int i = 0; // a static local variable
int j = 0; // not static
// ...
}
Builtin types such as int are not automatically initialized. Therefore you may get a warning when you try to read from that variable before having set it to something meaningful because it can hold just about anything.
Just because your particular compiler no longer gave you a warning does not mean that your variable is initialized properly. As a rule of thumb you should always explicitly initialize your variables to avoid accidentally reading from it without having set it first:
int i; // not initialized
int j = 0; // explicitly set to 0
Here is a link to the C++ Core Guidelines on the topic of initialization: https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es20-always-initialize-an-object, it may be worth a read.
A static variable can be defined like this:
int nextIndex()
{
static int index = -1;
return ++index;
}
So when you first call this function the static variable index will be initialized with -1;. The next line will increase index by 1 and return the result.
All subsequent calls of nextIndex will only execute the return ++index; part and skip the initialization.
Also static varibales are automatically initialized with zero if not implemented different.
So if you change above function to
int nextIndex()
{
static int index;
return ++index;
}
the first value it returns will be one. Also the first call won't initialize the index, but it will be initialized as soon as your program starts.

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).

string declaration before main funciton in C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i'm new to understanding stri and declaring them. can a string variable = "" ;
i'm confused why you could put a equal sign on a declaration also. is this to declare a function to be empty sort of like a global variable? like int variable = 0; is that sort of like a global string variable? once i change it it'll be stored down in main function and other fucntions?
#include<iostream>
using namespace std;
string variable = "";
int main() {
return 0;
}
The statement you're asking about defines a variable in
namespace scope (in this case, the global namespace). It's more
or less like any definition: except with regards to linkage and
lifetime:
The lifetime is static, which means that the variable will be
initialized before main is entered (in practice, anyway),
and will be destructed after exit is called.
The linkage is external, which means that the name variable
always refers to the same entity, even in different translation
units.
And of course, since the scope is namespace scope, the variable
can be directly referred to from any function in that namespace,
or in any namespace nested in that namespace. And since all
other namespaces are nested in the global namespace, that means
that the variable can be referred to everywhere (unless some
other declaration is hiding it).
You can assign value to a string variable in two ways.
string variable = "";
This means that you declared a variable named variable of type string and you assigned an empty string to this variable.
You can also assign value this way
string variable("");
this means exactly the same as the one above. but here you don't need the equal sign.
Here's a reference which can help you understand strings http://www.cprogramming.com/tutorial/string.html
There are four separate parts to the small example you posted:
1) Include the necessary headers:
#include<iostream>
2) Declare any used namespaces:
using namespace std;
3) Now this is what you are probably asking about:
string variable = "";
This line above is completely independent of the function below. It is declaring a global variable called variable, of type string. It is also assigning a value to it, which just happens to be the empty string i.e. "". You could also have said instead:
string variable = "My name is numLOCK";
So you are just initializing the value of that variable to the specified text assigning aome value to the variable.
4) Next comes the main function. This does the actual work.
int main() {
return 0;
}
Note that you can use the global variable declared above in your main or any other function. You can also declare more variables inside the function. For example:
string someText = "My name is numLOCK";
int main() {
int someNumber = 42;
cout << someText << endl;
cout << someNumber << endl;
return 0;
}
This will print out:
My name is numLOCK
42

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

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.