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?
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); /* ... */ }
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)
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With