2

Cannot convert from "void" to "int" in C++ - anyone know why? is there a function i have to use?

int calc_tot,go2;
go2=calculate_total(exam1,exam2,exam3);
calc_tot=read_file_in_array(exam);
Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
user320950
  • 187
  • 3
  • 7
  • 15
  • 1
    Which line is it occurring on? What are the return types of `calculate_total` and `read_file_in_array`? I'm guessing one of those returns a `void` type, which you can't convert to `int` because it doesn't make any sense. – Travis Gockel Apr 30 '10 at 20:25
  • 2
    What part of "cannot convert nothing to a number" is it that you're having problems with? – Lasse V. Karlsen Apr 30 '10 at 20:29
  • o sorry void calculate_total(exam1,exam2,exam3); void read_file_in_array(exam); – user320950 Apr 30 '10 at 22:23
  • if that is true how will i call that function thats what i am trying to do – user320950 Apr 30 '10 at 22:24
  • 1
    @user: You need to use a return type of `int` and return a value from the functions. If your current learning material doesn't cover this sufficiently, see here for good introductory books: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Georg Fritzsche Apr 30 '10 at 22:32

3 Answers3

3
go2=calculate_total(exam1,exam2,exam3);
calc_tot=read_file_in_array(exam);

My guess would be that one of those two functions returns a void, so you can't assign that value to an int. Since a "void" function doesn't return anything, you can't assign its return value to an int.

I would expect code like this to give you such an error:

void voidfunc () {
  // Do some things
}

int main () {
    int retval = voidfunc();
    return 0;
}

Though my compiler gives:

$ g++ main.c
main.c: In function ‘int main()’:
main.c:6: error: void value not ignored as it ought to be
WhirlWind
  • 13,974
  • 3
  • 42
  • 42
0

void is the same as saying no type. There is no information in a void. You cannot convert no information into a number, hence the error.

Perhaps if you give us more information about the types of your functions, or where the exact error occurred, we can help you more.

Yann Ramin
  • 32,895
  • 3
  • 59
  • 82
0

Per your comments, calculate_total is declared wrong. If the function needs to return a value, it should be declared as:

int calculate_total(/*...*/);

Notice the int in front of the function name, instead of void.

And in the function body:

int calculate_total(/*...*/)
{
  int total = 0;
  /* ... calculate the total */
  return total;  // Return the total.
}

If you insist on having a function returning void, you can add another argument to the function:

void calculate_total(int * total, /*...*/);

The function then becomes:

void calculate_total(int * total, /*...*/)
{
  if (total) /* check for null pointers */
  {
    *total = 0;
    for (/*...*/)
    {
      *total += /*...*/
    }
  }
  return;
}
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154