How to Fix error: expected primary-expression before ‘)’ token (C) in C++

The “error: expected primary-expression before ‘)’ token” occurs in C++ at a compile-time error message that suggests that there is a problem with the syntax of your code, specifically that a primary expression (a variable, constant, or expression that evaluates to a value) is expected before a closing parenthesis token (‘)’).

To fix the “error: expected primary-expression before ‘)’ token” error in C++, you must find and correct the incorrect syntax in your code.

Why the error occurs in the first place and fix it different ways

The error message usually means that you have an extra closing parenthesis somewhere in your code that is not matched with an opening parenthesis or a closing parenthesis without a corresponding opening parenthesis.

You will get this type of error if you have an unmatched parenthesis, a missing operator, or a missing semicolon.

C++ code that reproduces the error

#include <iostream>

int main() {
  std::cout << "Hello World!" );
  return 0;
}

Output

error: expected primary-expression before ')' token (C)

In this code, the error occurs because there is an extra closing parenthesis after the “Hello World!” string literal.

C++ code that fixes the error

#include <iostream>

int main() {
  std::cout << "Hello World!\n";
  return 0;
}

Output

Hello World!

Missing operator

If you try to operate on a value and have forgotten to include the operator, you will get this error.

#include <iostream>

int main()
{
  int x = 2;
  std::cout << x 2; // Incorrect syntax, missing operator
  return 0;
}

Output

error: expected ';' after expression

To fix this error, add the operator you want to use, such as “+”

#include <iostream>

int main()
{
  int x = 2;
  std::cout << x + 2 << "\n";
  return 0;
}

Output

4

Missing semicolon

You will get this error if you forget to include a semicolon after a statement.

#include <iostream>

int main()
{
  int x = 2;
  std::cout << x + 2
  return 0;
}

Output

error: expected ';' after expression

To fix this error, add the missing semicolon.

#include <iostream>

int main()
{
  int x = 2;
  std::cout << x + 2 << "\n";
  return 0;
}

Output

4

These are just a few examples of what can cause the “error: expected primary-expression before ‘)’ token” error.

You can see that the specific cause and solution for your error will depend on the context of your code and the syntax you are trying to use.

But the most common error is syntax, and always check your code before attempting to run.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.