c – Why am I getting void value not ignored as it ought to be?
c – Why am I getting void value not ignored as it ought to be?
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 youre 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);
/* ... */
}
The original poster is quoting a GCC compiler error message, but even by reading this thread, its not clear that the error message is properly addressed – except by @pmgs 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 arent allowed to assign void to integers, or any other type.
In the OPs 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, its important that this thread gives a succinct, clear, and easily findable result.
c – Why am I getting void value not ignored as it ought to be?
srand
doesnt return anything so you cant initialize a
with its return value because, well, because it doesnt return a value. Did you mean to call rand
as well?