Error void value not ignored as it ought to be

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:

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?

Tsakiroglou Fotis's user avatar

asked Jan 17, 2012 at 14:26

abc's user avatar

5

  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);
    /* ... */
}

answered Jan 17, 2012 at 14:29

pmg's user avatar

pmgpmg

105k12 gold badges125 silver badges198 bronze badges

6

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.

Community's user avatar

answered Jul 29, 2013 at 2:55

Jamin Grey's user avatar

Jamin GreyJamin Grey

9,9416 gold badges39 silver badges52 bronze badges

srand doesn’t return anything so you can’t initialize a with its return value because, well, because it doesn’t return a value. Did you mean to call rand as well?

answered Jan 17, 2012 at 14:29

CB Bailey's user avatar

CB BaileyCB Bailey

733k101 gold badges626 silver badges651 bronze badges

1

    int a = srand(time(NULL))
        arr[i] = a;

Should be

        arr[i] = rand();

And put srand(time(NULL)) somewhere at the very beginning of your program.

answered Jan 17, 2012 at 15:41

Shiplu Mokaddim's user avatar

Shiplu MokaddimShiplu Mokaddim

55.7k15 gold badges138 silver badges185 bronze badges

«void value not ignored as it ought to be»
this error occurs when function like srand(time(NULL)) does not return something and you are treating it as it is returning something. As in case of pop() function in queue ,if you will store the popped element in a variable you will get the same error because it does not return anything.

answered Oct 9, 2017 at 16:37

Afzal Ahmad's user avatar

im trying to build an rc plane using arduino nano and nrf24l01 as receiver but im having some issues in the code

it has error on the line
done = radio.read(joystick,sizeof(joystick)); which says that void value not ignored as it ought to be

the whole code is below

#include <nRF24L01.h>
#include <RF24.h>
#include <RF24_config.h>
#include <SPI.h>
#include<Servo.h>

Servo Throttle,Rudder,Elevator,LeftAileron,RightAileron ;

const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(9,10);
int joystick[5];

void setup()
{
  /*Serial.begin(9600);
  delay(1000);
  Serial.println("Starting Rx");*/ //Enable serial for debugging

  attachMotors();

  calibrateMotors();

  radio.begin();

  detachMotors();

  radio.setPALevel(RF24_PA_MAX);
  radio.setPayloadSize(10);
  radio.setDataRate(RF24_250KBPS);
  radio.setRetries(15,15);

  radio.openReadingPipe(1,pipe);
  radio.startListening();;
}

void loop()
{
  detachMotors();

  if(radio.available())
  {
    bool done=false;
    while(!done)
    {
      done=radio.read(joystick,sizeof(joystick));
    }

  attachMotors();

  int a=joystick[0];
  int b= joystick[1]; //stores values from tx
  int c=joystick[2];
  int d=joystick[3];
  int e=joystick[4];

  //Serial.println(a);
  //Serial.println(b);
  //Serial.println(c);
  //Serial.println(d);
  //Serial.println(e);
 // Serial.println(f);

  delay(20);
  Throttle.writeMicroseconds(a);   //write values to motor
  Rudder.write(b);
  Elevator.write(180-c);

  if(d== LOW)
  {
  LeftAileron.write(180); ////to activate right aileron
  RightAileron.write(180);
  delay(15);
  }

  else if(e == LOW)
  { 
    LeftAileron.write(0);  //to activate left aileron
    RightAileron.write(0);
    delay(15);
  }
  else
  {
    LeftAileron.write(100);
    RightAileron.write(110); //Ailerons at neutral pos
    delay(15);
  }
    }
  else
  {
    calibrateMotors();
    delay(15);

  }
  }

void attachMotors()
{
  Throttle.attach(3);
  Rudder.attach(4);
  Elevator.attach(5);
  LeftAileron.attach(6);
  RightAileron.attach(7); 
}

void calibrateMotors()
{
  Rudder.write(90);
  Elevator.write(90);
  LeftAileron.write(100);
  RightAileron.write(110); //centering servo shafts
}

void detachMotors()
{
  Throttle.detach();
  Rudder.detach();
  Elevator.detach();
  LeftAileron.detach();
  RightAileron.detach();
}

asked Jul 19, 2017 at 10:42

Osmond Yang's user avatar

2

Something changed while you were looking away. This is the updated description of read(). As you can see, it not longer returns a bool.
Use available to determine if packets are available:

/**
   * Read the available payload
   *
   * The size of data read is the fixed payload size, see getPayloadSize()
   *
   * @note I specifically chose 'void*' as a data type to make it easier
   * for beginners to use.  No casting needed.
   *
   * @note No longer boolean. Use available to determine if packets are
   * available. Interrupt flags are now cleared during reads instead of
   * when calling available().
   *
   * @param buf Pointer to a buffer where the data should be written
   * @param len Maximum number of bytes to read into the buffer
   *
   * @code
   * if(radio.available()){
   *   radio.read(&data,sizeof(data));
   * }  
void read( void* buf, uint8_t len );

answered Jul 19, 2017 at 10:55

4

Offline

Зарегистрирован: 17.01.2020

При компиляции возникает ошибка «void value not ignored as it ought to be». Помогите, ибо я в программировании стартер. Писал программу не я, так что за неё не ручаюсь. Библиотеку RF24 скачал, дело не в ней. Подскажите что куда написать, чтобы всё заработало. Буду ооооочень благодарен =)

Программа следующая :

#include <SPI.h>
#include <nRF24L01.h> 
#include <RF24.h> //Скачиваем и устанавливаем библиотеку RF24 для радио модуля!!!!!!!!!
#include <Servo.h>
Servo myservo1;
Servo myservo2;
Servo myservo3;
#define CE_PIN   2
#define CSN_PIN 9
int pwm = 0;
int pwm2 = 0;
const uint64_t pipe = 0xE8E8F0F0E1LL;
RF24 radio(CE_PIN, CSN_PIN); 
int joystick[9];
//unsigned long time;
void setup()   
{
  delay(50);
  radio.begin();
  radio.setChannel(9);
  radio.setDataRate(RF24_250KBPS);        // Установка минимальной скорости;
  radio.setPALevel(RF24_PA_HIGH);         // Установка максимальной мощности;
  radio.openReadingPipe(1,pipe);
  radio.startListening();
  myservo1.attach(4);
  myservo2.attach(8); 
  myservo3.attach(3);
  pinMode(7, OUTPUT);
  pinMode(10, OUTPUT);
  digitalWrite(10,LOW);
  pinMode(14, OUTPUT);
  pinMode(15, OUTPUT);
  pinMode(16, OUTPUT);
  pinMode(17, OUTPUT);
  pinMode(18, OUTPUT);
  pinMode(19, OUTPUT);
}


void loop()  
{
  if ( radio.available() )
  {
    bool done = false;
    while (!done)
    {
      done = radio.read( joystick, sizeof(joystick) );
      myservo1.write(joystick[0]);
      myservo2.write(joystick[2]);
      myservo3.write(joystick[4]);
      digitalWrite(14, !joystick[5]);
      digitalWrite(15, !joystick[6]);
      digitalWrite(16, !joystick[7]);
      digitalWrite(7, !joystick[8]);  
      
     if(joystick[1]>500 && joystick[1]<524)
{    digitalWrite(17,LOW);
     digitalWrite(10,LOW);
}
             if(joystick[1]>524)
             {   pwm = map(joystick[1], 524,1024,0,255);
                 analogWrite(5,pwm);
                 digitalWrite(17,LOW);
                 digitalWrite(10,HIGH);
             }
                         if(joystick[1]<500)
                         {   pwm = map(joystick[1],500,0,0,255);
                             analogWrite(5,pwm);
                             digitalWrite(17,HIGH);
                             digitalWrite(10,LOW);
                         }
                         
if(joystick[3]>500 && joystick[3]<524)
{    digitalWrite(18,LOW);
     digitalWrite(19,LOW);
}
             if(joystick[3]>524)
             {   pwm2 = map(joystick[3], 524,1024,0,255);
                 analogWrite(6,pwm2);
                 digitalWrite(18,LOW);
                 digitalWrite(19,HIGH);
             }
                           if(joystick[3]<500)
                           {   pwm2 = map(joystick[3],500,0,0,255);
                               analogWrite(6,pwm2);
                               digitalWrite(18,HIGH);
                               digitalWrite(19,LOW);
                           }          
  }
  }
  else
  {       
  }
  }

  1. 02-20-2018


    #1

    vead is offline


    Registered User


    error: void value not ignored as it ought to be

    I am getting this error: void value not ignored as it ought to be in my program. What is this error and how to remove it?

    Code:

    #include <stdio.h>
    
    void addition(int x, int y);
    
    
    int main(void)
    {
      	 int a = 10; int b = 20;
    	 
    	 int c;
    	 
    	 c = addition(10, 20);
    	 
    	 printf("addition = %d n",c);
    	 
        return 0;
    }
    
    
    void addition(int x, int y)
       {
    	   unsigned result;
    	   result = x +y ;
       }


  2. 02-20-2018


    #2

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    By making your function return an int, and not void.


  3. 02-20-2018


    #3

    vead is offline


    Registered User


    Quote Originally Posted by Salem
    View Post

    By making your function return an int, and not void.

    I understood where I was confuse
    addition with no return type but passing value

    Code:

    #include <stdio.h> 
    void addition(int x, int y);
     
     
    int main(void)
    {
         int a = 10; int b = 20;
          
         addition(10, 20);
          
        return 0;
    }
     
    void addition(int x, int y)
       {
           unsigned result;
           result = x +y ;
           
           printf("addition = %d",result);
       }

    addition with return type and passing value

    Code:

    #include <stdio.h> 
    int addition(int x, int y);
     
     
    int main(void)
    {
       
         int c;
          
         c = addition(10, 30);
         
         printf("addition = %d",c);     
        
         return 0;
    }
     
    int addition(int x, int y)
       {
           unsigned result;
           result = x +y ;
           
           
       }


  4. 02-20-2018


    #4

    Salem is offline


    and the hat of int overfl

    Salem's Avatar


    1. Your result should be int.
    2. You need a return statement.


azdws

0 / 0 / 0

Регистрация: 14.11.2015

Сообщений: 15

1

05.12.2015, 19:06. Показов 10273. Ответов 3

Метки нет (Все метки)


C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <conio.h>
#include <string>
 
using namespace std;
 
/* Function: Bubble sort */
void bubble_sort(int *a, int length) {
     for (int i = 0; i < length-1; i++) {
        for (int j = 0; j < (length-i)-1; j++) {
             if (a[j] > a[j+1]) {
                swap(a[j], a[j+1]);
             }
         }
     } 
 }
/* --------------------- */
 
/* Program body */ 
int main() {    
 
int *a = new int[10];
int i, length;
 
cout << "Enter elements of array: ";
for (i=0; i <= length; i++)
    {
    cin >> a[i]; cin >> length;
            
        int array_sort = bubble_sort(a, length);
        cout << array_sort  << " ";
        cout << endl;
    }   
    
/* ------------ */
}

Ошибка в строке 30:[Error] void value not ignored as it ought to be

Здравствуйте, как исправить данную ошибку? Спасибо!

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

05.12.2015, 19:06

Ответы с готовыми решениями:

Как исправить ошибку: Неявное преобразование типа «void» в «string» невозможно?
Как исправить ошибку в label3.Text=F(2, n, 0, m, a);//начальный делитель, число, начало массива,…

Исправить ошибку «C2562: ‘main’: ‘void’ function returning a value»
Привет программистам. Не могу разобраться с ошибкой &quot;C2562: ‘main’: ‘void’ function returning a…

Исправить ошибку error C2562: функция типа «void», возвращающая значение
Выдает ошибку error C2562: tabl: функция типа &quot;void&quot;, возвращающая значение.
#include &lt;iostream&gt;…

Как устранить ошибку variable or field declared void
Значит, сидел я тут, решал лабы, и вдруг… как говорится
На моменте описания функции probel…

3

Эксперт .NET

5858 / 4735 / 2940

Регистрация: 20.04.2015

Сообщений: 8,361

05.12.2015, 19:18

2

Лучший ответ Сообщение было отмечено azdws как решение

Решение

Цитата
Сообщение от azdws
Посмотреть сообщение

как исправить данную ошибку?

Удивлю, если скажу, что она здесь не единственная?
Правда остальные — логические:
1) length нужно инициализировать до цикла, даже до создания массива, а в цикле ее вводить не нужно
2) массив нужно создавать размерностью length
3) в заголовке цикла нужно условие i < length
4) в цикле не нужно сортировать массив
5) так как функция void, то ее результат нельзя ничему присвоить, так как его нет
6) не забыть освободить память



0



azdws

0 / 0 / 0

Регистрация: 14.11.2015

Сообщений: 15

05.12.2015, 22:55

 [ТС]

3

Спасибо! Разобрался, у меня вообще беда была в выводе. Исправленная часть:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* Program body */ 
int main() {    
 
    int *a = new int[10];
    int i, length;
 
cout << "Enter array's size':n"; 
cin >> length;
 
cout << "Enter elements of array:n";
    for (i=0; i < length; i++)
    {
    cin >> a[i];
    }
    
        bubble_sort(a, length);
        
            for (i=0; i < length; i++) 
            {
            cout << a[i] <<  " ";
            }
            cout << endl;
/* ------------ */



0



Даценд

Эксперт .NET

5858 / 4735 / 2940

Регистрация: 20.04.2015

Сообщений: 8,361

05.12.2015, 23:03

4

строку 4 исправьте на

C++
1
int *a = new int[length];

и перенесите на строку 9, чтобы иметь возможность работать с массивом любого размера

Добавлено через 3 минуты
и в конце функции main добавьте освобождение памяти:

C++
1
delete [] a;



1



Понравилась статья? Поделить с друзьями:
  • Error void type not allowed here
  • Error void is not a pointer to object type
  • Error vocaloid текст
  • Error vocaloid lyrics
  • Error vmerror принтер