Void funtion; code won't compile

If I change the function type to int, it will compile. Why won't it compile when I change it to void?



#include <iostream>
using namespace std;

void sum(float myArray[4][4]);


float main(void)
{

float myArray[4][4] = {{ 1, 3, -3, 4}, {4, 5, 3, -1}, {0, 3,-2, 1}, {9, 9, -9, 7}};
cout << sum(myArray) << endl;

return 1;
}

void sum(float myArray[4][4])
{
float total = 0;
for(int row = 0; row < 4; row++)
{
for(int colomn = 0; colomn < 4; colomn++)
{
total = total + myArray[row][colomn];
}
}

cout << "The sum is " << total << endl;

return;
}
void means the function will not return a value, why do you have a return statement in your sum function?
@Return 0, I don't think it matters. It complies either way.
I figured it out.
The error is because of the line
cout << sum(myArray) << endl;
in the code. When the function is declared void you cannot use it in a cout statement in the main.
You can only use the above cout statement, if the function returns something.
When I made my function return an integer, it was printing whatever I asked it to return.
Instead, I made it return a character. It complied and ran without printing anything extra. :)
Why not just call the function independently? The sum() function, if it is printing its result, shouldn't return anything and should just be called normally. Don't make it return an arbitrary value for no reason.

Though, IMO, sum() ought to return the total sum.
Topic archived. No new replies allowed.