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.
Related
I have a program that uses 3 separate files, a header file for function declarations, a cpp file for the definitions, and a main driver file to call the functions. For my function definitions, I have variables being created inside these functions that I wish to use as parameters for another function being called in main. I'm confusing myself just trying to put it into words, below is an example.
Header File
void function01(char);
void function02(int, int, char);
Cpp File
void function01(char a){
int var01 = 3;
int var02 = 4;
int var03 = 8;
char a = 'a';
}
void function02(int num1, int num2, int num3){
int sum = num1 + num2 + num3;
}
Main File
int main (void){
function02(var01, var02, var03);
return 0;
}
I know that as it is written now an error would be called. But is there anyway I can access the variables used in this first function so that I can call those same variables in main and pass them into my second function?
How to access the variables of a function inside main?
It is not possible to access non-static local variables of a function in a scope where that function is being called. Those variables exist only during function's execution. The objects named by the variables are created when the function is called, and destroyed before the function returns.
function01 is currently completely useless because it neither has any effects observable to the outside of the function, nor does it return anything. After calling the function the state of the program would be exactly the same as if you hadn't called the function. The function also doesn't do anything with its argument.
What you can do instead is return values from a function. It is only possible to return a single value. But you can group multiple objects inside a class. You could rewrite function01 like this for example:
struct my_example_class {
int var01;
int var02;
int var03;
char a;
};
my_example_class
function01(){
return {3, 4, 8, 'a'};
}
Then call the other function and use the returned member objects as arguments to the other function:
auto r = function01();
function02(r.var01, r.var02, r.var03);
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;
}
I have the following code:
int countLatticePoints(const double radius, const int dimension) {
static std::vector<int> point {};
static int R = static_cast<int>(std::floor(radius));
static int latticePointCount = 0;
for(int i = -R; i <= R; i++) {
point.push_back(i);
if(point.size() == dimension) {
if(PointIsWithinSphere(point,R)) latticePointCount++;
} else {
countLatticePoints(R, dimension);
}
point.pop_back();
}
return latticePointCount;
}
When I make the call countLatticePoints(2.05, 3) I get the result 13 which is correct. Now I change the parameters and then call countLatticePoints(25.5, 1) I get 51 which is also correct.
Now when I call countLatticePoints(2.05, 3) and countLatticePoints(25.5, 1) right after each other in the main program I get 13 and then 18 (instead of 51), I really don't understand what i'm doing wrong ? When I call each one individually without the other I get the correct result but when I call the functions together one after the other my results change.
You're misusing static.
The second time you call the function, you push additional values into point.
Edit: I hadn't spotted the recursion. that makes things more complex, but static is still the wrong answer.
I'd create a 'state' object, and split the function into two. One that recurses, and takes a reference to the 'state' object, and a second one which initialises the state object and calls the first.
struct RecurState
{
std::vector<int> point;
int latticePointCount
RecurState() : latticePointCount(0)
{
}
}
Outer function:
int countLatticePoints(const double radius, const int dimension)
{
RecurState state;
return countLatticeRecurse(radius, dimension, state)
}
Recursive function
int countLatticeRecurse(const double radius, const int dimension, RecurseState &state)
{
...
}
Local, static variables only get initialized once, on the first function call.
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.
Here I have written some code to get the square of a number from a function, but the return statement is not working as desired by me, it is giving me the same number which I have entered, I want to know the reason behind this, please if any one can explain this to me...
#include<iostream>
#include<conio.h>
using namespace std;
int square(int &i);
int main()
{
cout<<"enter the number whose square you want to find";
int a;
cin>>a;
square(a);
cout<<"the square of the number is"<<a;
_getch();
return 0;
}
int square(int &i)
{
return i*i;
}
You're ignoring the returned value. You should store it as:
int value = square(a);
cout<<"the square of the number is "<< value;
Also, as the type is just integral type, passing by reference doesn't give you much advantage. I would suggest to use pass by value for its readability sake:
int square(int i)
{
return i*i;
}
--
Or in case if you're experimeting with reference, and trying to learn it, then in that case I would say that you've to store the result of product in the argument itself, as:
int square(int &i)
{
i = i * i; //this updates i here, and at the call site as well
return i;
}
Or simply do this:
int square(int &i)
{
return i = i*i; //multiply, update, and return - all in one statement!
}
You do not obtain the result.
Your line should be:
a = square(a);
to fetch the result from the function.
The other possibility would be to write in the function
int square(int &i)
{
i = i * i;
return i;
}
The latter will alter the variable you passed to the function which justifies passing a reference.
To make it clear you want to alter the variable do something like:
void square(int &i)
{
i = i * i;
}
You see there is no return involved but it will alter the variables value.
You have a choice:
Modify the parameter you pass in, or
Return a value and assign it to something in the calling scope.
What you are doing in square is the second option. You seem to want the first.
If what you really want is to modify the passed-in value, then what you need is this:
void square(int &i)
{
i = i*i;
}
Either do it this way:
a = Square (a) ; // in main()
...
int Square (int i) // Pass by value -- doesn't change a in main
{
return i * i ;
}
or do it this way:
Square (a) ; // in main()
...
void Square (int& i) // Pass by reference -- changes a in main
{
i = i * i ; // No need for a return value
}
Make sure you understand the difference before you program anything else!
Judging by your comments on the answers, you've misunderstood what passing by reference does OR you've misunderstood return.
I'm assuming you're thinking that the variable i will be updated in your program. However, this is not the case. If you did something like...
i = i*i;
then yes, you would be correct. However, you did not assign any value to i, you simply multiplied it by itself and returned the result. Also, if you truly wanted to make this work based on a reference, there would be no need to return anything, as the variable would be updated via the reference.