void testing(){
cout << it << endl;
};
int main(){
int it = 99;
testing();
return 0;
}
This is probably a real rookie and basic question but how can i access the variable it within the function testing without passing it as an argument?
Or is the scope a function can access defined by where it is defined.
for example, testing defined in global scope, cannot access main function scope?
You can access the variable making it a global variable.
int it;
void testing(){
cout << it << endl;
};
int main(){
it = 99;
testing();
return 0;
}
But you should avoid using global variables. Since every function can access these it can be hard to figure out which functions actually access and modify these variables.
You should prefer passing variables between functions as it makes you code easier to read and you can avoid errors like unwanted value overrides.
Related
I want to access the value assigned to global variable in main function from the function. I don't want to pass argument in function.
I have tried referring different stack overflow similar questions and C++ libraries .
#include <iostream>
long s; // global value declaration
void output() // don't want to pass argument
{
std::cout << s;
}
int main()
{
long s;
std::cin >> s; // let it be 5
output()
}
I expect the output to be 5 but it shows 0.
To access a global variable you should use of :: sign before it :
long s = 5; //global value definition
int main()
{
long s = 1; //local value definition
cout << ::s << endl; // output is 5
cout << s << endl; // output is 1
}
Also It's so simple to use global s in cin :
cin >> ::s;
cout << ::s << endl;
Please try it online
You are declaring another variable s in your main function. line 7 of your code. and it's the variable which is used in cin. either delete that line or use :: before s.
long s;
cin >> ::s; //let it be 5
output();
It is important for you to know that the local variable s declared in main() and the variable s declared at file scope aren't identical despite the name.
Since the local variable s declared in the function main() shadows (see Scope - Name Hiding) the global variable s you have to use the Scope Resolution Operator :: to access the global variable s declared at file-scope:
#include <iostream>
long s;
void output()
{
std::cout << s; // no scope resolution operator needed because there is no local
} // s in output() shadowing ::s
int main()
{
long s; // hides the global s
std::cin >> ::s; // qualify the hidden s
output()
}
... or get rid of the local s in main().
That said using global variables (without real need) is considered very bad practice. See What’s the “static initialization order ‘fiasco’?. While that doesn't affect PODs it will bite you sooner or later.
You can do simply and use:: before the global variable or just remove the
long s;
From main() because as you are declaring local variable s in the main() function. The Global s and local s are different despite having the same name. lets learn more by the following example by giving local and Global variable different name.
#include <iostream>
long x; // global value declaration
void output() // don't want to pass argument
{
std::cout << x;
}
int main()
{
long s;
std::cin >> s; //here you are storing data on local variable s
output() // But here you are calling global variable x.
}
In main() function s is local and x is global variable and you are calling the global variable in output() function. you can use:: (scope resolution operator) for calling global x in main if u have the same naming or just call as it by variable name if they have a different name.
PS: If you have any question just do comment down hope this will help you and understand what's the mistake. Read more about the scope of the local and global variable here
You defined output() on the global scope which means it will refer to the long s variable on the global scope not the long s defined in main().
First of all, when you declare a global variable without assigning a value it automatically sets it's value to 0.
And another thing, you should know about your scope. The variable s in your main function has no existence in the output function.
In the output function , you are getting 0 because your global variable is set to 0.
You can just change you global variable's value by assigning different value to it.
long s; //global value declaration
void output() //don't want to pass argument
{
cout<<s;
}
int main()
{
cin>>s; //let it be 5
output()
}
So there is something called static initialization and dynamic initialization and apparently they do not describe a certain way of initializing but when things are initialized. Static and dynamic initialization can only used to designate initializations of non-local variables...
So what about local variables? When do their initializations happen and what is it called? I cannot find anything called local initialization? I mean wouldn't it be quite convenient to have a name for when they are initialized since value-/ aggregate-/ etc. initializations describe what initialization happens and the can even be used with static and dynamic initialization(as far as I know) which makes it just a bit more confusing to me..
Hope this made somewhat sense to you :)
Local variables are initialised when they are constructed.
When doesn't need a name, only what is interesting.
Local variables are initialized when the scope is entered/reentered.
There is no specific terminology in c++ for local variable initialization.
Consider following example
for (int i = 0; i < 5; ++i) {
int n = 0;
printf("%d ", ++n);
/* prints 1 1 1 - the previous value is lost
every time n is initialized with 0 when scope is entered
*/
}
Simple logic is all local variables (static or dynamic) get initiated when only they are called in run time.
class Test
{
public :
Test(string text)
{
cout << (text) << endl;
}
};
void print()
{
Test t1("local");
static Test t2 ("local static");
}
int main(int argc, char* argv[]) {
cout << "begin" << endl;
print();
cout << "end" << endl;
}
anwers
begin
local
local static
end
Here's an extremely basic example of my question.
#include <iostream>
#include <string>
using namespace std;
int x;
void test(int x) {
x += 3;
cout << x << endl;
}
int main() {
test(x);
cout << x << endl;
return 0;
}
the output is:
"3" (new line) "0"
How can I specify inside of the "test()" function that I want the class's 'x' variable to have the 3 added to it instead of the temp variable inside of the function?
In java you specify that you're dealing with the function/method's variable by using '"this". Is there a similar way to do this in C++?
In your case you can use :: to specify to use global variable,
instead of local one:
void test(int x) {
::x += 3;
cout << ::x << endl;
}
And it is not class member or so on just global and local.
In the C++ language, create a class or struct and you can use this->x the same as this.x in the Java language.
First of all, thank you for stating that you come from Java. This will help us a lot in terms of helping you!
Now, let's analyze your code
#include <iostream>
#include <string>
using namespace std;
Including some headers, using the std namespace (not recommended, BTW), everything's okay here.
int x;
You declare a variable named x of type int at global scope, with an initial value of zero (this only applies to objects at global scope!).
void test(int x) {
x += 3;
cout << x << endl;
}
You declare a function test that takes a parameter x of type int and returns void (a.k.a: nothing). The function increments the value of its intenral x variable by 3, then prints that to standard output by means of std::cout. Just to be clear, once you declare the int x parameter, it "hides" the int x at global scope, thus if you want to access the later, you have to use another way (see below).
int main() {
test(x);
cout << x << endl;
return 0;
}
You declare the special main function, taking no parameters and returning int. The function calls test with the global int x as argument, then prints the value of the global x to the standard output by means of std::cout, and finally returns zero, indicating successful execution.
Now, you have a big misconception, that you can attribute to the single-paradigm design of the Java language. In Java, there's no concept of "global functions", not to even say there are no "functions" at all. You only have "classes" with "methods".
In C++, this is not the case. The C++ language is a multi-paradigm one; it allows you to do imperative programming, structured programming, object-oriented programming, and even functional programming (you're not expected to have understood that last sentence completely)! When you declare anything without specifying an scope, it's said to lie in the global scope. The global scope can be accessed by anything, anywhere. In the example you presented there are no classes involved!
In the global scope, something like void test(int) is not a method, but a function. There's no class "owning" that function; let's say it's of "everyone" ;). A function is just a block of code that you can reuse by giving it arguments, if the function has them at all. In C++, you use classes to encapsulate data and corresponding code in a single "packed" black-box entity, not for, well, anything, like in Java.
Now, (this is somewhat like Java, but be careful!), when you pass a "plain" object, such as an int or something more funky and complex like std:: (you were not expected to understand that...) to a function, that function gets a copy of that object. The int x in test is not the same as the one main passed to it. If you assign to it inside test, you'll notice main "sees no difference". In Java, this applies too, but only to the fundamental types like int, but in C++ it does for all types.
If you want to be able to change the variable you got, just use references. You get a reference of any type T by typing T&. So, if you assign to a int& x inside the now modified test, main will "see" all changes.
Finally, there's the :: operator. It's used to access stuff in some scope from, well, other scopes. It has the form namespace-or-class::stuff. So for example, std::cout refers to identifier cout in namespace std. There's a special case: if the left operand is not given, :: accesses the global scope. This is useful whenever you "hide" something from the global scope. So, for example, in test, you could say ::x, and that would refer to the x in the global scope!
void test(int x) {
// ...
::x += 123;
}
Edit: If you're curious, you can take a glance at how classes in C++ work with this (I won't explain it, because that's off-topic)...
#include <iostream>
int x = 0;
class MyClass {
private:
int x;
public:
MyClass() : x(0) {}
void test(int x) {
this->report(x);
std::cout << "Doing some magic...\n";
this->x += x;
this->report(x);
}
void report(int x) {
std::cout << "this->x = " << this->x << '\n';
std::cout << "x = " << x << '\n';
}
};
int main() {
MyClass c;
c.report();
x += 123;
c.test(x);
x += 456;
c.test(x);
c.report();
}
I'm trying make number guessing game with qt creator. I need to access a variable from another function. I was able to do that on python by adding "self." to beggining of variable but I can't do it on C++. Here's a sample what I am trying to do:
void function1()
{
int i;
}
void function2()
{
I need to access i here.
}
Thanks for help.
You could use pointers, classes or global variable ( I'd recommend pointers or a class tho)
void f1(int *iPtr)
{
cout << "value= " <<*iPtr << endl;
}
void f2(int *iPtr)
{
*iPtr = *iPtr + 5; // access ( modify ) variable here
cout << "after addition = " << *iPtr << endl;
}
int main()
{
int i = 5;
int *iPtr;
iPtr = &i; // point pointer to location of i
f1(iPtr);
f2(iPtr);
// after f1() value of i == 5, after f2() value of i == 10
}
I believe the equivalent behavior in C++ would be a member variable.
If you're not already, I'd suggest using a class. So, in your header file define it something like this:
class MyClass {
public:
void function1();
void function2();
private:
int i;
};
If you're not using C++ classes, then you can define "i" in the header file but that will make it global - in essense. And, probably not the best practice.
It is not possible to access a variable from another function since they exist only on the stack and they are destroyed when the function exits. Use a global variable.
You could declare i as a global variable and just assign it the random number once you have chosen it. That way you could still generate a random number and use it in another function.
int i;
void function1()
{
int randNum;
// get random number here
i = randNum;
}
void function2()
{
// do stuff with i here
}
I am trying to define few global variables which should be available all functions but would like to initialize from main program. Can anyone help me with the syntax? Please note that still a bit beginner with c++ classes etc. As I need to run the same copy of this program multiple times and don't want to have a same shared class across multiple instances of this program - need to ensure I create a new class in the main body. Also wanted to mention - printvars - is a pre-built function for me and I don't have control over passing any pointer variables to it - just that I can only use global variables in that function.
class gvars
{
public:
int x=0;
int y=0;
gvars() {}
~gvars() {}
};
std::unique_ptr<gvars> *g=NULL; // Must be a pointer to class
//I can't pass any parameters to this function
//Only have control over the body of the program to access global vars
void printvars()
{
std::cout << (*g).x << " " << (*g).y << std::endl;
}
int main()
{
if (g==NULL)
{
g=new gvars(); // This is critical - create a new class here only
}
(*g).x=10;
(*g).y=20;
printvars(); // Expected output : 10 20
delete g;
return 0;
}
Code is good except only line.
Try change
std::unique_ptr<gvars> *g=NULL; // Must be a pointer to class
to
gvars*g=NULL;
Program will create/delete new instance of your class on each run for sure. Also printvars should work fine.