Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Need explanation for this code in c++?
I need the output for this question and also the explanation for the usage of global variable i.e where it is used and how its value changes.
Void d(int&x , int y , int z)
{
a+=6;
y*=a;
z=a+y;
cout<<x<<'\t'<<y<<'\t'<<z<<endl;
}
Void main()
{
int a=15, b=5;
d(::a,a,b);
Cout<<::a<<'\t'<<a<<'\t'<<b;
}
1 Answer
- husoskiLv 77 years agoFavorite Answer
A global variable is one that is not defined inside of any function. You are using (a) as a global variable in function d() by using it without a local variable declaration. You are also using (a) as a global variable in main() by using the ::a syntax, which says to use global definition of a.
However, you don't provide a global declaration of a in the code posted. Add something like:
int a = 3;
...at the top of your program, after #include and using lines, before any function definitions. That will create a global version of (a) that is created and initialized to 3.
I suppose that "Void" and "Cout" are pasting artifacts. They must be "void" and "cout" in your program. Speaking of "void", that's not allowed as the return type for main(). The return type for main() must be int in a standard C++ program. Change to "int main()" and add a "return 0;" statement just before the closing brace.
The d() function is strange. It accepts an int argument x as a reference, meaning that changes to x will be stored in the caller's argument variable, but does not change x in the function. It accept a value argument z, but overwrites it with (a+y) without ever looking at the value that the caller passed.
Modified program:
#include <iostream>
using namespace std;
int a=3;
void d(int &x , int y , int z)
{
a += 6;
y *= a;
z = a+y;
cout << x << '\t' << y << '\t' << z << endl;
}
int main()
{
int a=15, b=5;
d(::a, a, b);
cout << ::a << '\t' << a << '\t' << b;
return 0;
}
Output:
9 135 144
9 15 5
As you can see, the final value of the global version of a had 6 added to it, and the local versions of a and b in main were not changed, since they were passed as value arguments y and z. That is, copies of the values of a and b were passed to (and altered by) d() as the y and z arguments, but those value argument copies are discarded when d() returns.