(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.
Related
In the following call-by-value example, I cannot understand why this code is not changing the value of the 5 to a 6.
Line 11 calls the function changeValue which has the value 6, so I would have thought 6 should be output, however 5 is still output?
#include <iostream>
using namespace std;
void changeValue(int value);
int main()
{
int value = 5;
changeValue(value);
cout << "The value is : " << value << "." << endl;
return 0;
}
void changeValue(int value)
{
value = 6;
}
// This doesn't change the value from 5 to 6. 5 is output?
When you pass a function argument by value a copy of the object gets passed to the function and not the original object.Unless you specify explicitly arguments to functions are always passed by value in C/C++.
Your function:
void changeValue(int value)
receives the argument by value, in short a copy of value in main() is created and passed to the function, the function operates on that value and not the value in main().
If you want to modify the original then you need to use pass by reference.
void changeValue(int &value)
Now a reference(alias) to the original value is passed to the function and function operates on it, thus reflecting back the changes in main().
The value of value isn't changing because your int that you pass to the function is being copied into the stack frame of the function, then it's being changed, and when the function exits the copy is destroyed. The original in main's stackframe has not changed, since it was copied to the changeValue.
If you want to change it, you should pass a reference to an int, like so void changeValue(int& value), which says that the value isn't copied into the function, but merely an alias to the original is passed.
The behavior being observed currently is because passing by value means a copy of value (new integer with value of value) is actually passed to the function.
You have to pass by reference. For that the changeValue function will look like this:
void changeValue(int& value)
Rest of the code will remain the same.
Passing a variable by reference means the same int value declared in main is passed to the changeValue function.
Alternatively, you can pass a pointer to value to the changeValue function. That will however, require changes to how you call the function also.
int main()
{
int value = 5;
changeValue(&value);
...
return 0;
}
void changeValue(int* value)
{
*value = 6;
}
I'm including this answer as another way to think about writing functions and passing parameters by value.
You could also have written this code in the following way. That is pass the parameter by value, modify the local copy in the function, which does not alter the original value, and return the altered value.
int changeValue(int val)
{
val = 6;
return val;
}
int main()
{
int value = 5;
value = changeValue(value);
cout << "The value is : " << value << "." << endl;
return 0;
}
I am not in any way indicating my suggestion for your program is better than passing by reference. Instead, it is just the way learning a functional programming language (Clojure) is affecting the way I think.
Also, in languages like Python, you cannot modify a scalar parameter. You can only return a new value. So my answer is more of an exercise in thinking about things differently in C/C++.
AND:
the copy is assigned 6, but the change is not returned.
you need some reference or pointer if you want to change the value:
try using a method signature like:
void changeValue(int& value)
that will probably do what you expected
This is because the change in the changeValue () function is local. When you can changeValue (value) the contents of the variable value in main is copied in the formal argument named value (same name) of the function. Same name does not mean that the both are same. The value you are accessing inside the function is a copy of the value you had in the main.
To change you either need to pass it by reference or a pointer
void changeValue (int *val)
{
*val = 6;
}
call with changeValue (&value) in main
This works because the address of the variable value in main is passed and this address value is copied into val of the function. By doing *val we can get the contents of the address which was copied into val, which in actually the contents of value in main.
OR
void changeValue (int &val)
{
val = 6;
}
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 have a function that has a variable called static const int initial_var = some_var so that on subsequent runs to the function, initial_var is guaranteed to not change. The issue is however the function may be called for different some_vars and because initial_var is used in calculations, this can screw things up.
func() is meant to operate on DIFFERENT variables, all named some_var. Their state needs to be remembered so I use a static const variable, but that will only remember the state for ONE variable.
void func()
{
static const int initial_var = some_var;
some_var = initial_var; // This is the part where things may screw up if some_var
// is a different variable
}
What's an elegant way to fix this?
You say you need "Their state needs to be remembered" so you can just put them in an array.
int array[10]; // 10 elements.
int count = 0;
void storeVariable(int temp)
{
array[count] = temp;
count++;
// Reset if full.
if(count >= 10)
count = 0;
}
That seems fairly simple enough.
I’ve a bit confusion about static, auto, global and local variables.
Somewhere I read that a static variable can only be accessed within the function, but they still exist (remain in the memory) after the function returns.
However, I also know that a local variable also does the same, so what is the difference?
There are two separate concepts here:
scope, which determines where a name can be accessed, and
storage duration, which determines when a variable is created and destroyed.
Local variables (pedantically, variables with block scope) are only accessible within the block of code in which they are declared:
void f() {
int i;
i = 1; // OK: in scope
}
void g() {
i = 2; // Error: not in scope
}
Global variables (pedantically, variables with file scope (in C) or namespace scope (in C++)) are accessible at any point after their declaration:
int i;
void f() {
i = 1; // OK: in scope
}
void g() {
i = 2; // OK: still in scope
}
(In C++, the situation is more complicated since namespaces can be closed and reopened, and scopes other than the current one can be accessed, and names can also have class scope. But that's getting very off-topic.)
Automatic variables (pedantically, variables with automatic storage duration) are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered.
for (int i = 0; i < 5; ++i) {
int n = 0;
printf("%d ", ++n); // prints 1 1 1 1 1 - the previous value is lost
}
Static variables (pedantically, variables with static storage duration) have a lifetime that lasts until the end of the program. If they are local variables, then their value persists when execution leaves their scope.
for (int i = 0; i < 5; ++i) {
static int n = 0;
printf("%d ", ++n); // prints 1 2 3 4 5 - the value persists
}
Note that the static keyword has various meanings apart from static storage duration. On a global variable or function, it gives it internal linkage so that it's not accessible from other translation units; on a C++ class member, it means there's one instance per class rather than one per object. Also, in C++ the auto keyword no longer means automatic storage duration; it now means automatic type, deduced from the variable's initialiser.
First of all i say that you should google this as it is defined in detail in many places
Local
These variables only exist inside the specific function that creates them. They are unknown to other functions and to the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the function that created them is completed. They are recreated each time a function is executed or called.
Global
These variables can be accessed (ie known) by any function comprising the program. They are implemented by associating memory locations with variable names. They do not get recreated if the function is recalled.
/* Demonstrating Global variables */
#include <stdio.h>
int add_numbers( void ); /* ANSI function prototype */
/* These are global variables and can be accessed by functions from this point on */
int value1, value2, value3;
int add_numbers( void )
{
auto int result;
result = value1 + value2 + value3;
return result;
}
main()
{
auto int result;
value1 = 10;
value2 = 20;
value3 = 30;
result = add_numbers();
printf("The sum of %d + %d + %d is %d\n",
value1, value2, value3, final_result);
}
Sample Program Output
The sum of 10 + 20 + 30 is 60
The scope of global variables can be restricted by carefully placing the declaration. They are visible from the declaration until the end of the current source file.
#include <stdio.h>
void no_access( void ); /* ANSI function prototype */
void all_access( void );
static int n2; /* n2 is known from this point onwards */
void no_access( void )
{
n1 = 10; /* illegal, n1 not yet known */
n2 = 5; /* valid */
}
static int n1; /* n1 is known from this point onwards */
void all_access( void )
{
n1 = 10; /* valid */
n2 = 3; /* valid */
}
Static: Static object is an object that persists from the time it's constructed until the end of the program. So, stack and heap objects are excluded. But global objects, objects at namespace scope, objects declared static inside classes/functions, and objects declared at file scope are included in static objects. Static objects are destroyed when the program stops running.I suggest you to see this tutorial list
AUTO:C, C++
(Called automatic variables.)
All variables declared within a block of code are automatic by default, but this can be made explicit with the auto keyword.[note 1] An uninitialized automatic variable has an undefined value until it is assigned a valid value of its type.[1]
Using the storage class register instead of auto is a hint to the compiler to cache the variable in a processor register. Other than not allowing the referencing operator (&) to be used on the variable or any of its subcomponents, the compiler is free to ignore the hint.
In C++, the constructor of automatic variables is called when the execution reaches the place of declaration. The destructor is called when it reaches the end of the given program block (program blocks are surrounded by curly brackets). This feature is often used to manage resource allocation and deallocation, like opening and then automatically closing files or freeing up memory.SEE WIKIPEDIA
Difference is static variables are those variables: which allows a value to be retained from one call of the function to another.
But in case of local variables the scope is till the block/ function lifetime.
For Example:
#include <stdio.h>
void func() {
static int x = 0; // x is initialized only once across three calls of func()
printf("%d\n", x); // outputs the value of x
x = x + 1;
}
int main(int argc, char * const argv[]) {
func(); // prints 0
func(); // prints 1
func(); // prints 2
return 0;
}
Local variables are non existent in the memory after the function termination.
However static variables remain allocated in the memory throughout the life of the program irrespective of whatever function.
Additionally from your question, static variables can be declared locally in class or function scope and globally in namespace or file scope. They are allocated the memory from beginning to end, it's just the initialization which happens sooner or later.
static is a heavily overloaded word in C and C++. static variables in the context of a function are variables that hold their values between calls. They exist for the duration of the program.
local variables persist only for the lifetime of a function or whatever their enclosing scope is. For example:
void foo()
{
int i, j, k;
//initialize, do stuff
} //i, j, k fall out of scope, no longer exist
Sometimes this scoping is used on purpose with { } blocks:
{
int i, j, k;
//...
} //i, j, k now out of scope
global variables exist for the duration of the program.
auto is now different in C and C++. auto in C was a (superfluous) way of specifying a local variable. In C++11, auto is now used to automatically derive the type of a value/expression.
When a variable is declared static inside a class then it becomes a shared variable for all objects of that class which means that the variable is longer specific to any object.
For example: -
#include<iostream.h>
#include<conio.h>
class test
{
void fun()
{
static int a=0;
a++;
cout<<"Value of a = "<<a<<"\n";
}
};
void main()
{
clrscr();
test obj1;
test obj2;
test obj3;
obj1.fun();
obj2.fun();
obj3.fun();
getch();
}
This program will generate the following output: -
Value of a = 1
Value of a = 2
Value of a = 3
The same goes for globally declared static variable. The above code will generate the same output if we declare the variable a outside function void fun()
Whereas if u remove the keyword static and declare a as a non-static local/global variable then the output will be as follows: -
Value of a = 1
Value of a = 1
Value of a = 1
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.