// C to C++ conversion
#include <iostream>
#include <vector>
const int N = 40;
inline void sum(int *p, int n, const std::vector<int>& d) {
*p = 0;
for (int i = 0; i < n; ++i) {
*p = *p + d[i];
}
}
int main() {
int accum = 0;
std::vector<int> data(N);
for (int i = 0; i < N; ++i) {
data[i] = i;
}
sum(&accum, N, data);
std::cout << "Sum is: " << accum << std::endl;
return 0;
}
Why is const int better than #define?
It has type safety (#define doesn’t care what type it is).
It respects C++ scoping rules (macros don’t respect namespaces).
Debuggers understand const variables, but they don’t track macros.
Why use int p instead of return?
This function modifies accum directly in memory via the pointer.
This mimics how C functions typically modify values passed by reference.
However, in modern C++, it’s cleaner to use int& p instead of int* p.
Why pass std::vector& d by const reference?
Prevents unnecessary copying of the entire vector.
const ensures the function can’t modify d accidentally.
Without const, passing a vector by reference (vector& d) allows modifications.
Why std::vector instead of a plain array?
No need for malloc/free like in C.
Dynamic resizing (though we’re not using it here).
Memory safety: avoids out-of-bounds access if used properly.
Why do we pass &accum instead of returning a value?
C++ style would be to return int instead of modifying via pointer.
This is still very C-like, since we’re explicitly using pointer manipulation.