Question:
Simple C++ Question - Variable Not Increasing?
anonymous
2009-05-31 08:00:27 UTC
Why does the the element variable not increase in my code below? I don't get why the value stays at 0. I'm familliar with Java and this works in Java and prints out 10.

#include
#include
using namespace std;

class Simple{
private:
public:
int element;
};

void increment (Simple s){
s.element = s.element +1;
}
int main() {
Simple s;
int i;

s.element = 0;
for (i=0; i<10; i++){
increment(s);
cout << "new value: " << s.element << "\n";
}
return (0);
}
Five answers:
meow
2009-05-31 10:43:10 UTC
Good answer by Silent (thumbs up).



To fix your problem, just place an ampersand in the increment prototype:



void increment (Simple &s){ // that's it; program will now work

s.element = s.element +1;

}
anonymous
2009-05-31 08:27:59 UTC
I don't have a C++ compiler right now on my computer but I believe you have just stumbled upon the blessing and curse of C++... the almighty pointer.



When you call "increment(s);" in your code you are passing a copy of the s variable, not the actual s variable. Therefore, the copy gets updated and your actual value doesn't. When you call increment again on your next iteration, you send the original s (which is still 0) and the process happens again.



To get around this you need to use what is called a pointer (I suggest finding a pointer tutorial online to help you understand). Once you learn a bit about pointers, substitute "Simple *s;" for "Simple s" in your main code and change the rest of your code accordingly.



Java does not have pointers, which would be why this would work in Java and not in C++.



And actually, there is another way to solve this problem I believe. If you put the increment function inside the Simple class definition, then you should be able to call "s.implement()" and have the function work as intended.
Silent
2009-05-31 08:29:16 UTC
The parameter to your increment() function is going to be passed by value. This means that a copy of the variable is made, and the function operates on that — the original data is unaffected.



Java passes primitive (e.g., int, char) by value, but it passes object types by reference-value, which is the behavior you're looking for. C++ passes everything by value unless you tell it otherwise.
anon
2009-05-31 10:48:27 UTC
Passing objects as arguments



You need a & (ampersand) in the method. To pass by reference.



(Simple& s)
?
2016-12-13 08:37:40 UTC
char x[]="rama"; it is appropriate as compiler can locate out how plenty memory is needed in the process the compilation time itself. although, it truly is not suitable char x[]; x="rama"; because of comparable reason, yours isn't suitable


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...