How can i access global variable using function in c++? - c++

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()
}

Related

what is the problem with declaring a variable bounded by a parameter in the function itself rather than in the main function?

I have been trying to include the declaration of the variable in the function itself but it doesn't work unless I include it in the main function. Why does this happen?
#include<iostream>
using namespace std;
function1(int x)
{
int x =1;
cout << x << endl;
return 0;
}
int main ()
{
function1( x);
return 0;
}` `
Welcome to the world of C++ coding! Looks like there's more than a few issues in the code here - let's break it down and see what we can find.
First and foremost, to answer your original question, your declaration of x (in function1) was made outside of the function you tried to use the variable in (in main). C++ can't normally see variables you declare in one function when it's running in another; that's by design, and is called scope.
To start, the code won't compile for a number of reasons, first and foremost the presence of stray backticks in your code at the very end. These need to be removed.
int main ()
{
function1( x);
return 0;
}` ` //<-- the ` ` will make the compiler angry
Now let's have a look at what's causing the error: x isn't yet declared. In C++, a variable has to be "declared" before it can be used. Since "x" hasn't been declared before its use in function( x);, the compiler kicks it back since it doesn't know what "x" means. Try this:
int x = 0;
function1( x);
We're not quite done yet, though. Once we make this change, the compiler will throw another error: In function 'int function1(int)': 8:5: error: declaration of 'int x' shadows a parameter. You've already included an int x in the definition of function1; by creating another int x inside function1, you've steamrolled your original x. Let's change that from a definition to an assignment.
function1(int x)
{
x =1;
cout << x << endl;
return 0;
}
Getting clsoer, but we've got one more error: 6:16: error: ISO C++ forbids declaration of 'function1' with no type [-fpermissive]. THis is telling you function1 needs to have a return type, which is a keyword in front of the function's name that tells the compiler what type of data it returns (void if it doesn't return any). Looks like you're using return 0; - why not return an int?
int function1(int x)
Now, at last, we've got code that compiles and runs.
#include<iostream>
using namespace std;
int function1(int x)
{
x =1;
cout << x << endl;
return 0;
}
int main ()
{
int x = 0;
function1( x);
return 0;
}
Try it here!
Good luck!
Why does this happen?
It happens because x is now undefined in the context where you're using it in main, and it's already defined (as a parameter) in the context where you're trying to define it in function1().
In the first case, you'll definitely get an error because x as used in main is completely undefined... the compiler is going to look at that function1(x) call and wonder what the heck it's supposed to supply for the x.
In the latter case, the compiler might let you redefine x, but it'll probably at least issue a warning. Also, if it's allowed, then your function1() will always print out 1 regardless of what you pass in for the x parameter because the newly declared x will be used instead of the value passed in the parameter.
The concept that you're missing is called scope. Every variable has a scope, which is essentially the realm in which it's known. The scope of a variable can be global, in which case it's available to the entire program, or limited to a single file, or it can be declared inside a function or block, in which case it's local to that block of code.
int x = 12; // x is available anywhere in the file and has initial value 12
void foo(int x)
{
cout << x << endl; // prints the value passed to foo by the caller
int x = 34; // this new x hides the parameter and is available
// anywhere inside this function, but not outside
cout << x << endl; // prints the new x, i.e. 34
{
cout << x << endl; // still prints 34
int x = 97; // hides the previous x, available only within
// this block or sub-blocks
cout << x << endl; // prints 97
} // x from the enclosed block goes out of scope
cout << x << endl; // prints 34, because we're back to the x at function scope
}
Understanding scope is very important because variable names are often duplicated, either on purpose or by accident, and you need to be able to tell where a given variable is in scope and therefore valid to use, and when it's not.

Accessing variables from scopes

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.

Specifying class variables vs. method variables C++

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();
}

Functions and variable declaration in C++

In the following code, why must int nInteger be declared inside int readNumber()'s body, but int nAnswer must be declared inside the () portion of void writeAnswer()? Declaring int nInteger inside the () or declaring int nAnswer inside the function body causes the IDE to complain about too few arguments for said function. Why does this happen?
I'm using Code::Blocks and the included MinGW on a Windows 7.
#include <iostream>
int readNumber()
{
using namespace std;
cout << "Please enter an integer: ";
int nInteger;
cin >> nInteger;
return nInteger;
}
void writeAnswer(int nAnswer)
{
using namespace std;
cout << "The sum is: " << nAnswer << endl;
}
int main()
{
int x;
int y;
x = readNumber();
y = readNumber();
writeAnswer(x+y);
return 0;
}
So basicly the int readNumber() function does not require any argument to be passed. You declare a local variable so the function knows where to assign the value you type in. You declare variable int nInteger and then in the very next line you assign a value to it by calling cin >> nInteger. If there was no variable declared then your program wouldn't know where to store the value that you type in.
You can think of it as of a basket for apples. You have one basket but no apples in it, then someone gives you 2 apples that you put into the basket. In the end the return statement work like you give the basket to someone else.
Function void writeAnswer on the other hand requires an argument to be passed. As you can see there in local variable declared. What it does is to simply display "The sum is: PASSED_ARGUMENT". So basicly if you call your writeAnswer function with number 6 like writeAnswer(6) it will write "The sum is: 6".

Static variables in C++

I ran into a interesting issue today. Check out this pseudo-code:
void Loop()
{
static int x = 1;
printf("%d", x);
x++;
}
void main(void)
{
while(true)
{
Loop();
}
}
Even though x is static, why doesn't this code just print "1" every time? I am reinitializing x to 1 on every iteration before I print it. But for whatever reason, x increments as expected.
The initialization of a static variable only happens the first time. After that, the instance is shared across all calls to the function.
I am reinitializing x to 1 on every iteration
No, you're not: you're initializing it to 1, but it only gets initialized once.
static doesn't mean const.
From MSDN:
When modifying a variable, the static
keyword specifies that the variable
has static duration (it is allocated
when the program begins and
deallocated when the program ends) and
initializes it to 0 unless another
value is specified. When modifying a
variable or function at file scope,
the static keyword specifies that the
variable or function has internal
linkage (its name is not visible from
outside the file in which it is
declared).
A variable declared static in a
function retains its state between
calls to that function.
When modifying a data member in a
class declaration, the static keyword
specifies that one copy of the member
is shared by all instances of the
class. When modifying a member
function in a class declaration, the
static keyword specifies that the
function accesses only static members.
The value of static is retained between each function call, so for example (from MSDN again):
// static1.cpp
// compile with: /EHsc
#include <iostream>
using namespace std;
void showstat( int curr ) {
static int nStatic; // Value of nStatic is retained
// between each function call
nStatic += curr;
cout << "nStatic is " << nStatic << endl;
}
int main() {
for ( int i = 0; i < 5; i++ )
showstat( i );
}
In your example, x will increment as expected because the value is retained.
static in this context means that value should be retained between calls to the function. the initialization is done only once.