开发者

cannot convert from "void" to "int"

开发者 https://www.devze.com 2022-12-28 23:40 出处:网络
Cannot convert from \"void\" to \"int\" in C++ - anyone know wh开发者_运维技巧y? is there a function i have to use?

Cannot convert from "void" to "int" in C++ - anyone know wh开发者_运维技巧y? 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);


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


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.


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消