I am learning c++ and I came across a really odd phenomenon in a program. I haven't seen any documentation on this problem. Why is that when I initialize a variable inside of a conditional statement it isn't recognized outside of it? Is the variable local to the conditional statement?
Here is an example:
#include "stdafx.h"
#include <iostream>
using namespace std;
/*scope / range of variables */
int global;
int main()
{
int local = rand();
cout << "value of global " << global << endl;
cout << "value of local " << local << endl;
int test = 10;
if (test == 0)
{
int result = test * 10;
}
cout << "result :" << result << endl;
return 0;
}
In this case result is undefined. Can someone please explain what is going on?
As pointed out in the comments, your declaration of result is local inside the if() blocks scope you provided:
if (test == 0)
{ // Defines visibility of any declarations made inside
int result = test * 10;
} // ^^^^^^
Hence the statement
cout << "result :" << result << endl;
would lead to a compiler error, since result isn't visible for the compiler at this point outside that scope.
But even if you declare result correctly outside of the scope block, your logic
int result = 0; // Presumed for correctness
int test = 10;
if (test == 0)
{
result = test * 10; // Note the removed declaration
}
doesn't make much sense, since test was given the value 10 immediately before testing it against the value 0 in your your if() statements condition, and the condition never would become true.
Related
Say I have a function that I want to call multiple times. At the start of this function I have declared an integer for a value of zero, and at the end of it I increased its value by one. Now I want to save the new value so when I call the function again the value of that variable becomes 2. Is there a way to do that besides getting the variable from another function or declare it at the top of line codes out of the functions?
TLDR
Yes, using the static keyword.
It changes the lifetime of the object declared with it, that becomes available for the whole duration of the program.
That said, you should be careful with using static local variables, because you're adding a state to the function execution.
#include <iostream>
using namespace std;
void printX()
{
static int x;
cout << "x: " << x << endl;
++x;
}
int main()
{
for (int i = 0; i < 10; ++i)
printX();
}
https://www.jdoodle.com/iembed/v0/909
There's more to the static keyword and you should look into it.
I'd suggest you read at least a couple of articles about it:
https://en.wikipedia.org/wiki/Static_(keyword)#Common_C
https://www.geeksforgeeks.org/static-variables-in-c/
you can use a static variable declared inside the function, since it is static the initialization to zero will happen only once and the rest of the time you call the function it will retain its value...
here is an example:
#include <iostream>
void foo(int x)
{
static int counter{0};
std::cout<< "this is x: " << x << std::endl;
counter++;
std::cout<< "this is counter: " << counter << std::endl;
}
int main() {
foo(1);
foo(10);
std::cout<< "something else in the app is executed... " << std::endl;
foo(101);
return 0;
}
and here the output:
this is x: 1
this is counter: 1
this is x: 10
this is counter: 2
something else in the app is executed...
this is x: 101
this is counter: 3
I am practice with C++ and I see some problem:
#include <iostream>
#include <string>
using namespace std;
int main() {
int a = 2;
{
cout << a;
cout << "\n";
float a = a / 2;
cout << "a= a/2 = ";
cout << a;
}
cout << "\n";
a = 2;
{
cout << a;
cout << "\n";
float b = a / 2;
cout << "b= a/2 = ";
cout << b;
}
}
This return:
2
a= a/2 = 0
2
b= a/2 = 1
I want to know why a = a/2 = 0 ?
Thank you
This is a subtle error. Look at this code:
int a = 2;
{
float a = a / 2;
}
Outside of the curly braces, the name a refers to int a, the integer declared up top. But inside the curly braces, once you reach the line in which float a is declared, the name a refers to float a inside the braces rather than int a outside the braces.
This is a problem because the line
float a = a / 2;
means "create a new variable named a of type float. Oh, and it needs an initial value. That's okay! Give it the value of float a, divided by two." See the problem here? The variable a is being initialized in terms of itself, so when a / 2 is computed a has not been initialized and the results are undefined.
To fix this, simply give float a a new name.
Because you are actually using declared, but never initialized variable when you stated float a = a/2. My computer prints 4.49985e-039 but that could be any number.
You are confusing yourself because you have two int & float variable with same name. Better to choose your name of the variable carefully or you have to track your code to see which is indicating which.
I'll comment on the each line which variable a has been used.
#include <iostream>
#include <string>
using namespace std;
int main() {
int a = 2; // int a declared in main scope used;
{
cout << a; // int a declared in main scope; since there is no a declared in local scope.
cout << "\n";
float a = a/2; // block scope variable a used without initialization to initialize itself. UB.
cout << "a= a/2 = "; // block scope variable used
cout << a; // block scope variable used
}
cout << "\n"; a = 2; // int a declared in main scope; Since it's block scope is within main scope only.
{
cout << a; // int a declared in main scope; since no a has been declared in local scope
cout << "\n";
float b = a/2; // int a declared in main scope; since no a has been declared in local scope
cout << "b= a/2 = "; // int a declared in main scope; since no a has been declared in local scope
cout << b;
}
}
I have this piece of code:
#include <stdio.h>
// global variable definition
int x = 0;
void access_global(){
cout << "ACCESSING FROM access_global()" << endl;
if (x > 0){
cout << "LOCAL VARIABLE" << endl;
cout << x << endl;
}
else{
cout << "GLOBAL VARIABLE" << endl;
cout << x << endl;
}
}
int main(int, char*[])
{
// declare new variable in given scope with same name as global variable
int x = 1;
cout << "ACCESSING FROM main()" << endl;
if (x > 0){
cout << "LOCAL VARIABLE" << endl;
cout << x << endl;
}
else{
cout << "GLOBAL VARIABLE" << endl;
cout << x << endl;
}
access_global();
return 0;
}
It outputs:
ACCESSING FROM main()
LOCAL VARIABLE
1
ACCESSING FROM access_global()
GLOBAL VARIABLE
0
Why is access_global() not accessing x in the main() scope?
Is it possible to modify access_global() function that it will show primary x variables from main() scope and if they are not defined then show those defined outside of main()? If is not possible can you please explain why? Thanks
Why is access_global() not accessing x in the main() scope?
Because main::x is not in scope in access_global. Fortunately, names don't just "leak" out of functions' scopes. The global x is the only x it can see.
Is it possible to modify access_global() function that it will show primary x variables from main() scope and if they are not defined then show those defined outside of main()?
Not in the way you are hoping to, no. The names in main are not related to the names in access_global in any sense.
If is not possible can you please explain why?
As usual: Because the standard says so. Why it does that is subject to some speculation, but it would certainly be extremely confusing if the meaning of some function changed depending on what names exist in the calling context, something you usually don't control when writing a function.
Just think what would happen if access_global was called once from a function that has some x, possibly not even of type int, and once from some function that does not have a local x: You could not predict what the function does at all without looking at all callers. That's very much impractical.
In the following program:
#include <iostream>
using namespace std;
int main(){
int i = 99;
for(int i = 1; i <= 10; i++)
{
cout << i << endl;
}
cout << endl << endl;
cout << i << endl;
return 0;
}
I am not getting an error on compilation.
My question is why this is happening.
The int variable i was declared twice. The first time i was declared in the main() function and thus its scope will be this whole main() function including the for loop. The second time i was declared with the for loop and thus its scope will be only the for loop. So, now inside the scope of the for loop there exists two int variablesi. Shouldn't this be a cause of error? And if not why?
Second thing is the output I am getting:
1
2
3
4
5
6
7
8
9
10
99
I also don't understand the output. Why after the execution of the for loop, the value of i that is being printed is 99 and not 10.
You can define variables with the same names in different scopes. The first variable i is defined in the scope of the main function. In the loop there is another implied nested and anonymous scope for the variables you declare for the loop.
For the compiler, the code
for(int i = 1; i <= 10; i++)
{
cout << i << endl;
}
is more or less equivalent to
{
int i;
for(i = 1; i <= 10; i++)
{
cout << i << endl;
}
}
I am trying to create a integer variable in a if statement body like this:
if (a == 72){
cout <<"You Are CORRECT1"<<endl;
int aa = 1;
}
else{
cout <<"No. The answer is "<<12*6<<endl;
int aa = 2;
}
When I compile this it says:
42 C:\Documents and Settings\Valued Customer\Desktop\C++\Variable.cpp aa undeclared (first use this function)
Could you please help me.
Declare the variable before like so.
int aa;
if (a == 72)
{
cout <<"You Are CORRECT1"<<endl;
aa = 1;
}
else{
cout <<"No. The answer is "<<12*6<<endl;
aa = 2;
}
Your variable declaration is correct, the problem ís that the lifetime of your variable is only valid inside the block in which it was declared. Any attempts to use it outside this block is invalid.
You can use the conditional operator for this kind of situation:
int aa = a == 72 ? 1 : 2;
This allows you to initialize a variable based on a condition, something which cannot be done with an if-else statement. You will have to deal with writing to stdout separately though.
It's likely telling you this when you're outside of your if/else statement. In the example you give, you're creating local variables inside the scope of the if and the else. They go out of scope and "cease to exist" after the if / else stuff.
Here's the way you should do it:
int aa = -1;
if (a = 72)
{
cout << "You are CORRECT1" << endl;
aa = 1;
}
else
{
cout << "No. The answer is " << 12 * 6 << endl;
aa = 2;
}
cout << aa << endl;
By doing it this way, you declare the int outside of the scope of the if/else code block, so the variable continues to survive, and can be accessed outside of that code block.