Reputation: 681
I'm trying to get the hang of pointers and addresses in C++ and am having trouble with functions with changing parameters.
The code below is writing Loop run #1.
in an infinite loop, instead of incrementing the value foo
.
My question is: What is the issue with this code here?
#include <iostream>
void Statement(int *foo) {
std::cout << "Loop run #" << *foo << ". ";
foo++;
}
int main() {
int foo = 1;
for (;;) {
Statement(&foo);
}
}
Upvotes: 1
Views: 158
Reputation: 310910
If I have understood correctly what you are trying to do then the function should be declared the following way as it is shown in the demonstrative program
#include <iostream>
void Statement(int *foo) {
std::cout << "Loop run #" << *foo << ". ";
++*foo;
}
int main() {
int foo = 1;
for (; ; ) {
Statement(&foo);
}
}
That is in an infinite loop you are trying to output incremented value of foo
.
In this case you have increment the value itself pointed to by the pointer like
++*foo
If you want to limit loop iterations then you can use for example an object of the type unsigned char and define the loop the following way
#include <iostream>
void Statement( unsigned char *foo) {
std::cout << "Loop run #" << int( *foo ) << ". ";
++*foo;
}
int main() {
unsigned char foo = 1;
for (; foo ; ) {
Statement(&foo);
}
}
Upvotes: 1
Reputation: 36463
You're incrementing a copy of the pointer itself, not what it points to. You probably meant:
(*foo)++;
This still won't fix the infinite loop though because you have nothing to stop it with.
Upvotes: 8
Reputation: 2434
Your issue is that you're incrementing the pointer, not the pointed-to data.
replace
foo++
with
(*foo)++
to increment the pointed-to value.
Upvotes: 5