Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting "void value not ignored as it ought to be"?

Tags:

c

I have the following function :

void getdata(int arr[], int n) {      for (int i = 0; i < n; i++)      {         int a = srand(time(NULL));         arr[i] = a;     } } 

And I call it in main:

getdata(arr, 1024); 

I get "void value not ignored as it ought to be" but I don't understand what is wrong.Why do I get this error?

like image 412
abc Avatar asked Jan 17 '12 14:01

abc


2 Answers

  int a = srand(time(NULL)); 

The prototype for srand is void srand(unsigned int) (provided you included <stdlib.h>).
This means it returns nothing ... but you're using the value it returns (???) to assign, by initialization, to a.


Edit: this is what you need to do:

#include <stdlib.h> /* srand(), rand() */ #include <time.h>   /* time() */  #define ARRAY_SIZE 1024  void getdata(int arr[], int n) {     for (int i = 0; i < n; i++)     {         arr[i] = rand();     } }  int main(void) {     int arr[ARRAY_SIZE];     srand(time(0));     getdata(arr, ARRAY_SIZE);     /* ... */ } 
like image 112
pmg Avatar answered Oct 03 '22 19:10

pmg


The original poster is quoting a GCC compiler error message, but even by reading this thread, it's not clear that the error message is properly addressed - except by @pmg's answer. (+1, btw)


error: void value not ignored as it ought to be

This is a GCC error message that means the return-value of a function is 'void', but that you are trying to assign it to a non-void variable.

Example:

void myFunction() {    //...stuff... }  int main() {    int myInt = myFunction(); //Compile error!      return 0; } 

You aren't allowed to assign void to integers, or any other type.

In the OP's situation:

int a = srand(time(NULL)); 

...is not allowed. srand(), according to the documentation, returns void.

This question is a duplicate of:

  • error: void value not ignored as it ought to be
  • "void value not ignored as it ought to be" - Qt/C++
  • GCC C compile error, void value not ignored as it ought to be

I am responding, despite it being duplicates, because this is the top result on Google for this error message. Because this thread is the top result, it's important that this thread gives a succinct, clear, and easily findable result.

like image 24
Jamin Grey Avatar answered Oct 03 '22 20:10

Jamin Grey