- #1
ChrisVer
Gold Member
- 3,378
- 465
I am not sure that I understand the following:
Why would someone pass an input to a function that he/she doesn't want to modify? And suppose that I want to do that, for example a function that runs a loop over [itex]N[/itex] events determined within the main and gives [itex]x=\sum_{i=1}^N i[/itex].
where in my function I don't really modify N at all...
VS just changing the type ##N## points to to const int.
They both operate the same. Any feedback?
http://www.cplusplus.com/doc/tutorial/pointers/One of the use cases of pointers to const elements is as function parameters: a function that takes a pointer to non-const as parameter can modify the value passed as argument, while a function that takes a pointer to constas parameter cannot.
Why would someone pass an input to a function that he/she doesn't want to modify? And suppose that I want to do that, for example a function that runs a loop over [itex]N[/itex] events determined within the main and gives [itex]x=\sum_{i=1}^N i[/itex].
C:
#include <iostream>
#include <cstdlib>
int fun(int* N){
int i,x=0;
for(i=1;i<=(*N);i++) x+=i;
return x;
}
int main(){
int myint=5;
int* N= &myint;
std::cout<< fun(N);
system("pause");
return 0;
}
where in my function I don't really modify N at all...
VS just changing the type ##N## points to to const int.
C:
#include <iostream>
#include <cstdlib>
int fun(const int* N){
int i,x=0;
for(i=1;i<=(*N);i++) x+=i;
return x;
}
int main(){
int myint=5;
const int* N= &myint; //no prob with conversion int*->const int*
std::cout<< fun(N);
system("pause");
return 0;
}
They both operate the same. Any feedback?