Originally Posted by
King Mir
The second will preform better, unless the compiler can itself realize that the two are functionally equivalent. I don't think most can.
Because of possible aliasing, the two are not necessarily functionally equivalent, e.g.,
Code:
#include <iostream>
int foo1(int array1[], int array2[],int array3[], int size){
int product=1;
for (int i = 0; i < size; i++)
product *= array1[i];
for (int i = 0; i < size; i++)
array3[i] = array1[i]+array2[i];
return product;
}
int foo2(int array1[], int array2[],int array3[], int size){
int product=1;
for (int i = 0; i < size; i++) {
product *= array1[i];
array3[i] = array1[i]+array2[i];
}
return product;
}
void print(int numbers[], int size)
{
for (int i = 0; i < size; ++i)
{
std::cout << numbers[i] << " ";
}
std::cout << std::endl;
}
int main()
{
{
int x[] = {1, 2, 3, 4, 5};
int y[] = {5, 6, 7, 8};
int result = foo1(x, y, x + 1, 4);
std::cout << "result = " << result << std::endl;
print(x, 5);
print(y, 4);
}
{
int x[] = {1, 2, 3, 4, 5};
int y[] = {5, 6, 7, 8};
int result = foo2(x, y, x + 1, 4);
std::cout << "result = " << result << std::endl;
print(x, 5);
print(y, 4);
}
}