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 pop
ed 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 push
ed, 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 pop
ed 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