Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I wish to declare a variable w inside a recursive function. I have to declare it as f(a) (some function of a) where a is a parameter of the function. The problem is that the function is recursive and w changes value every time the recursive function is called (since a changes)
Is there a way to do keep w fixed to its first initialization?
#include <iostream>
using namespace std;
void foo(int a)
{
if(a==1) return 0;
// int w = f(a);
//...some more lines of code that use 'w'
// eg. return foo(a - 1);
}
The best way to implement a variable that keeps its state between function calls is to use the static keyword.
int AddOne_Static(void) {
static int a;
a++;
return a;
}
int AddOne(void) {
int a;
a++;
return a;
}
int main(void) {
printf("%d\n", AddOne_Static());
printf("%d\n", AddOne_Static());
printf("%d\n", AddOne_Static());
printf("%d\n", AddOne());
printf("%d\n", AddOne());
printf("%d\n", AddOne());
}
The Output will be:
1
2
3
1
1
1
This is a much cleaner way of declaring a variable that will keep its value between calls than a global which will also pollute the global namespace unnecessarily.
You could use a constant if you want to make 'w' a constant. Defining a constant may differ according to the language.
In your case, you cannot use w as a constant since the value of w is changed when the function gets recursive.
But if you need a constant which does not change its value over the runtime of the program, then, you definitely can define a constant globally or inside the function and use the value.
Hope you got your answer. :)
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have an exercise like that. The requirement is to write code in the section
#include <iostream>
int minus (int a, int b) {
return a - b;
}
void calculate(int a, int b)
{
int (*myfunc)(int, int);
// STUDENT ANSWER BEGIN
// STUDENT ANSWER END
int ans = (*myfunc)(a, b);
printf("Output of calculation is %d.\n", ans);
}
int main() {
calculate(1,2);
return 0;
}
When I write
int (*myfunc) (int, int) = add;
int temp = (*myfunc)(a, b);
cout << temp;
the value of temp = -1 as expected (just for test) but I can't get the value of ans. So, I figure that two *(myfunc) is different. How can I fix that?
Thank you very much!
When you write:
int (*myfunc) (int, int) = add;
you are creating a new variable named myfunc. If you do it inside the same scope as the original myfunc, it is a compilation error, but if you write it inside a new scope (which the indentation of the code you pasted suggest, even if you haven't showed the brackets), you are shadowing the original variable with the new one. By using the name myfunc inside that scope, you are referring to the new variable.
The solution is simple. Instead of declaring a new variable, simply assign to the existing one:
myfunc = add; // or minus
EDIT: I misread the question and interpreted "but I can't get the value of ans" as "but I can't get the value into ans". But I'll leave this answer here in case that is what OP meant...
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Is it possible to declare a variable without assigning value in C++?
int a; int a=15; Which one will be Correct?
If i assign value to a variable 3 times or more which one will count at the end in C++??
int a=15;
int a=10;
int a=5;
Which value will be execute for a at the end?
int a; // declared but not assigned
a = 1; // assigning a value
a = 2; // assigning a different value
a = 3; // assigning another value
std::cout << a << "\n"; // will print 3 since only the last assignment matters
int x; declares a variable x without assigning a value.
If you assign to a variable three times then which ever assignment executed last will be the variables final value. Very important idea, C++ statements execute in a specific order, and which order they execute in is essential to understanding what a program does.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
int function(int a, int b){
a = a*b;
return(a);
}
This is a really stupid questions but, if i pass in 4 and 2.
Why doesnt the a need to be declared?
int function(int a, int b){ // two variables, a and b, are declared and set equal to whatever you passed in when you called the function.
a = a*b; // now you are using the two already-declared variables
return(a); // return the value of 'a' which was declared in the first line and then modified
}
Note that 'a' and 'b' in the above example are now destroyed. They only live inside of the function and are re-created every time you call function() with new values passed in. You can't call the 'a' and 'b' you were using in this function anywhere outside of this function, because they doesn't exist outside of this function. This means that you can declare another 'int a' and 'int b' outside of this function.
If I call this function in main:
int oldA = 5; // declare an int called oldA and set it to 5
int oldB = 10; // declare an int called oldB and set it to 10
cout << function(oldA, oldB); // makes a copy of oldA and oldB and then uses them inside function()
// note that oldA and oldB are still 5 and 10. A copy of them was made and then
// used inside of function.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
My function is supposed to return a local variable. It manages to do this without any compiler issues even though variable is out of scope.
int add(int a, int b);
{
int result=0;
result = a + b;
return (result); // result scope should be limited to this method
}
int main()
{
int res=0;
res = (3 + 4);
printf("Result : %d \n", res);
return 0;
}
Can anyone please explain this behavior.
When you do
return (result);
result is returned by value. So, the caller gets a copy of the value in result, and uses this copy subsequently. result itself goes out of scope, and is not accessed again.
If your variable was instead a pointer, it would be incorrect. You can read more about it from this question.
In addition, you seem to have forgotten to use add() at all. I suppose you meant to use
res = add(3,4);
in main() instead of
res = (3 + 4);
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Which is faster when assigning a variable via a method, to return a variable, or to point to a variable?
Case 1:
Function Declaration
void foo(int* number)
{
*number = 5;
}
Usage
int main()
{
int number;
function(&number);
cout << "Number: " << number;
}
Case 2:
Function Declaration
int foo()
{
int number = 5;
return number;
}
Usage
int main()
{
int number;
number = function();
cout << "Number: " << number;
}
PS: In case 2, I created a variable and returned it instantly. I know this doesn't make sense, but this is the closest example I can find for the situation I'm dealing with, since I'm initializing an actual object, which requires creating the object first, editing it, then returning it
It depends on the cost of copying the variable. For primitive types, return a value.
For more complex types consider passing in a reference, or take a look at the C++11 move semantics.
One benefit of using output parameters (Case 1) is it gives you the ability to have a function 'return' multiple values:
void foo (int* x, int* y)
{
*x = 5;
*y = 4;
}
But like everyone said in the comments, this doesn't matter in C++ as much as C.
Generally returns are far more readable and make your program's logic well defined and
easy to follow. In C++, stick to returns or references.
Typically, you should choose which to use on your needs rather than on performance.
Do you have multiple outputs? -> Use pointers
Is an input going to be an output -> Might as well use pointers
It's more difficult with these two scenarios to return a variable.
Other than that, performance-wise, it's only nice to use a variable when the variable is super complex, that way, you're only passing in a pointer instead of that super complex object. But any performance gain is negligible other than that.