Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

void
expression
invalid
c++
error

How to resolve the "invalid use of void expression" error in C++

Educative Answers Team

The “invalid use of void expression” error occurs in C/C++ when we try to assign a call to a void function to a variable. It also occurs when a void function is cast to another data type.

Code

In the following code, the function f() has a void return type. This function is passed as an argument to the function g(), which expects an int as its argument. C++ tries to cast the void return type of the function f() to an integer, which causes the “invalid use of void expression” error.

#include <iostream>
using namespace std;

void f()
{
  cout<<"Hello World"<<endl;
}

int g(int k)
{
	return (k+5);
}

int main()
{
	int x = g(f());
  cout<<x<<endl;
}

Solution

The solution is to avoid casting void return types to any other data type. Since the function g() can only accept an integer data type, we should only pass it data of integer data type.

#include <iostream>
using namespace std;

void f()
{
  cout<<"Hello World"<<endl;
}

int g(int k)
{
	return (k+5);
}

int main()
{
  f();
	int x = g(5);
  cout<<x<<endl;
}

RELATED TAGS

void
expression
invalid
c++
error
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring