Can anyone explain the output?
#include<iostream>
using namespace std;
int &fun(){
static int x = 10;
return x;
}
int main(){
fun() = 30;
cout << fun();
return 0;
}
output is 30
That's how static locals work - they persist the value between the function calls. Basically fun() has a static local and returns a reference to it, the effect is roughly the same as you would have with a global variable.
You return the static by reference, so when you do fun() = 30 you change it.
It's pretty clear, no?
Basically, foo() returns a reference to x.
When you call fun()a static variable is created and you return the reference to it. Basically, because of the static, the variable is not destroyed even if you exit the scope of the function. You affect the reference with 30 and then recalling the function you get 30 (the x at the second call is exactly the same at the first call). Basically the static works like a global variable in this case.
AS fun is the reference to the function so when you write this line
fun() = 30; it stores 30 in its return value i.e x, that is why you are getting the output as 30.
Related
am a c++ beginner and this code really confused me:
int global = 100;
int& setGlobal()
{
return global;
}
int &a=setGlobal() ;
int main(void){
a=a+5;
std::cout<<global<<std::endl;
}
The return type of setGlobal is int& , but global is an int.
Please explain to me how does that work?
Shouldn't it be return &global ?
The code that i understand is like this:
int global = 100;
int& x=global;
int& setGlobal()
{
x+10;
return x;
}
int main(void){
x=x+10;
std::cout<<global<<std::endl;
}
Maybe my problem is with references.
A return type of T& gets you the reference of the returned object of type T.
In your case
int& setGlobal()
{
return global;
}
returns a reference (int&) to global. Basically an alias, another way to access the same variable.
This means that
int &a=setGlobal() ;
Sets a as a reference to global and any operation on a is reflected on global.
It should come as no surprise that
int main(void){
a=a+5;
std::cout<<global<<std::endl;
}
prints 105. a and global are effectively interchangeable in your main scope (because one is an alias of the other).
If setGlobal returned &global, it would be returning the address of global. The address is the actual location of the variable in memory, it's not an alias. If you wanted to work with pointers, your code would look like this instead:
#include <iostream>
int global = 100;
int* setGlobal()
{
return &global;
}
int* a=setGlobal() ;
int main(void){
*a=*a+5;
std::cout<<global<<std::endl;
}
Notice how we can't access the contents of global using a directly (it's just an address). We must first dereference it.
And for good measure, you should also know that, since setGlobal() returns a reference to global in your example, it can be used directly as an lvalue to access global like so:
setGlobal() += 5;
Putting the above statement just before printing will result in "110" being displayed. Fun stuff! I invite you to read about lvalues and rvalues on your own time as a next step in your C++ journey!
void Animation::playAnimation() const
{
static const int index = 0;
const std::string& animationFileName = m_animationContainer.getAnimationName(index);
static const int zOrder = -1;
static bool isLooping = false;
AnimationBank::play(animationFileName,
zOrder,
isLooping);
}
what are pros and cons to define constant local variables as static?
what is an overhead of defining index, zOrder, isLooping as static. Is there any benefit to do this?
In general case if you declare a static variable inside of a function then it will be initialized during first use. In order to achieve this behavior another global static variable of boolean type will be created by the compiler. It will be initially set to false and then set to true after related static variable is initialized.
In your case there is no point to declare any variables as static.
Yes, you will have a little bit overhead when using static variables in function, since each time your program execute that function it has to check whether these static variables initialized.
Let's start with the easy one.
const:
const doesn't give you any ovehead and the only advantage it give you is the variable can't be changed during its life time. It is interesting because:
Correctness.
If want a that show clearly show what the variable, use const make clear that variable won't/can't be changed.
You may think, why I don't use a #define for example. Well, define will make the compiler replace it to fix values and in some cases it is not and advantage like strings or objects.
Protection.
If someone else qill use your function you make clear this variable can be changed and you protect its value.
Static:
Static give you a overhead because after create the variable for the first time it will exist during the lifetime of your program and the advantage is exactly that. When the variable is create you give it an value. Because it stay alive after that, no matter what happens, it can't get again a value as it the is the first time.
Lets see an example with class.
Suppose you want a class to manager an addition to one int and this int need to accumulate this additions including a new object of this class is created and or destroyed:
#include <iostream>
using namespace std;
class ClassAcInt {
public:
void Print_iVar();
void Add_iVar();
private:
static int iVar;
};
int ClassAcInt::iVar = 10; //iVar = 10
void ClassAcInt::Print_iVar() { //Show iVar
cout << iVar << '\n';
}
void ClassAcInt::Add_iVar() { //Add 1 to iVar
iVar++;
}
int main () {
ClassAcInt* oC1 = new ClassAcInt(); //iVar = 10
oC1->Print_iVar(); //print iVar
oC1->Add_iVar(); //iVar = iVar + 1
oC1->Print_iVar(); //Print iVar
delete oC1; //Bye what we did... Are you sure?
ClassAcInt* oC2 = new ClassAcInt(); //iVar = 10? Are you sure?
oC2->Print_iVar(); //Print iVar.... What a hack!!!!
oC2->Add_iVar(); //iVar = iVAr + 1
oC2->Print_iVar(); //omgosh...
delete oC2;
}
You can think the result will be:
10
11
10
11
but 'surprisingly' the result is:
10
11
11
12
The key is the lines static int iVar; and int ClassAcInt::iVar = 10;. Try to suppress the static word and see what happens :)
I'm trying to use a static variable as a counter for the number of times a function has been called. Essentially, I'm having function A call function B a number of times, and I want function B to return that value to function A so it can be displayed. An example of my test code is below(here main is function A and showStat is function B). As of now the output is 012340; the desired output is 012344. Thanks in advance.
int showStat()
{
static int statNum;
cout<<statNum; //function check
statNum++;
return statNum;
}
int main()
{
int statNum;
for( int i = 0; i < 5 ; i++)
{
showStat();
}
cout<<statNum;
return 0;
}
In main, change
showStat();
to
statNum = showStat();
You have two variables called statNum. Apparently the counting takes place in the static variable inside showStat() function. But in main() without reading the return value of showStat(), you are just printing the uninitialized local variable, which the compiler happened to assign an initial value 0.
(This is the question asked of me.)
What is the output from the following program? Explain your results.
int val = 20;
int func1()
{
int val = 5;
return val;
}
int func2()
{
return val;
}
int main()
{
// (1)
cout << func1() << endl;
// (2)
cout << func2() << endl;
}
Output::
5
20
---I am assuming it is like this because:---
func1 changes val from 20 to 5.
func2 changes nothing.
I believe the val is modified by each function and stored separately.
Could someone explain this, tell me what subject I should look at?
int val = 20;
int func1()
{
int val = 5;
return val;
}
The above creates two variables named val. One is global, and the other is local to scope of func1.
When you are inside the scope of func1, the local val hides the global one. You therefore do not change the value of the global variable, and simply return what you stored in the local val.
int func2()
{
return val;
}
func2 returns the value of the global variable (which wasn't changed). And that is why you see the output you noted.
If you want to refer to the global variable, despite having a local, you can use the scope resolution operator ::.
int val = 20;
int func1()
{
int val = 5;
::val = 10;
return val;
}
The above will set the global val to 10.
func1 changes val from 20 to 5.
No, it is returning the local variable as it is. Not changing the global var. Innermost scoped var overtakes outer var with same name.
func2 changes nothing.
True. It is returning the global var without change. This function call be may optimised away by compiler altogether.
I believe the val is modified by each function and stored separately.
Incorrect, none of the function is doing any change to value.
Further, have a look at storyteller answer for scope resolution operator :: concepts.
You are declaring val as 20 at a global level, so func2() will just return that.
In func1(), you declare val as 5, then return that. The global variable is ignored for the scope of the method.
If you are confused about this, I would read up on scope.
func1 creates a local variable with value 5 and returns it. The global variable remains unchanged.
func2 return the global variable whose value is 20.
func1 changes val from 20 to 5
Incorrect.
func1 uses a local variable named val whose value is 5. It does not change the value of the global variable of the same name.
func2 changes nothing.
Correct. It just returns the value of the global variable val.
I believe the val is modified by each function and stored separately.
Incorrect. Neither function, as posted, modifies the global variable val. The global value is not stored separately for each function. func1 uses a local variable of the same name and does not touch the global variable at all. func2 accesses the value of the global variable but does not modify it.
Let me tell you a story, assume you are living in a small town namely, SmallTown. Your neighboring town is, Hello. There is a coincidence too and that is the city you are living in is also named Hello. Now, your mother asks you to go to Hello and get some bread. What would be your first reaction? You will go to neighboring town, right. After a week you have to go to another city. Now, somebody asks you, "When are you going back to Hello?". Which "Hello" are you thinking about now? The city, right.
To your problem,
The int variable you are going to access depends on your scope. If you are inside a function i.e., if your scope is local and there is local defined same name and same type variable, it will be accessed before the globally defined variable.
Both of the variables are different and will have different memory addresses, so NO,
func1 changes val from 20 to 5
This is not true. Both are different just as the town and city.
Of course func2 changes nothing, as it looks for the val and reaches the global defined variable as if it was out of the city.
Again, no I believe the val is modified by each function and stored separately. And I think you know the answer to this now.
Consider the following code snippet in C++:
#include <iostream>
using namespace std;
int &fun()
{
static int a = 10;
return a;
}
int main(int argc, char const *argv[])
{
int &y = fun();
y += 30;
cout << fun();
return 0;
}
Output: 40
How is output of the code snippet given above justified?
fun isn't a function pointer, it's a nullary function that returns an int&. Specifically, it returns a reference to a static int named a.
So what your program does is:
int &y = fun(); // this is the first call to fun, so we initialize a.
// it now has a value of 10, and we return a reference to it
// so y is a reference to the static variable local to fun()
y += 30; // y == 40
// since y is a reference to "fun::a", a is now 40 too
cout << fun(); // a is static, so it will only get initialized once.
// that first line is effectively a NOOP, so fun() just
// returns a reference to it. which has a value of 40.
You are not using function pointers, but just storing the result of a call to fun in a reference.
a is static variable, and you are initialising a reference to that variable. A reference is just another name for a, in this case, so that's why modifying the value of the reference y, you modify also the value a, which is static, that means that its value is preserved from call to call.