proposed code corrections:
search for: ‘<<—‘ to find corrections
#define lefttrig 13
#define leftecho 12
#define righttrig 9
#define rightecho 8
int leftred = 4;
int leftgreen = 5;
int rightred = 6;
int rightgreen = 7;
#include <SoftwareSerial.h> //эту библиотеку надо скачать
#include <TinyGPS.h> //эту библиотеку надо скачать
SoftwareSerial mySerial(2, 3); // RX, TX от модуля
TinyGPS gps;
void gpsdump(TinyGPS gps);
void printFloat(double f, int digits = 2);
void setup()
{
mySerial.begin(9600);
pinMode(lefttrig, OUTPUT); //инициируем как выход
pinMode(leftecho, INPUT); //инициируем как вход
pinMode(righttrig, OUTPUT); //инициируем как выход
pinMode(rightecho, INPUT); //инициируем как вход
pinMode(leftred, OUTPUT);
pinMode(leftgreen, OUTPUT);
pinMode(rightred, OUTPUT);
pinMode(rightgreen, OUTPUT);
digitalWrite(leftgreen, HIGH) ; // led system diagnostic
digitalWrite(leftred, HIGH) ; // led system diagnostic
digitalWrite(rightgreen, HIGH) ; // led system diagnostic
digitalWrite(rightred, HIGH) ; // led system diagnostic
delay(2000);
digitalWrite(leftgreen, LOW) ; // led system diagnostic
digitalWrite(rightgreen, LOW) ; // led system diagnostic
delay(2000);
digitalWrite(leftred, LOW) ; // led diagnostic ok
digitalWrite(rightred, LOW) ; // led diagnostic ok
}
unsigned int impulseTimeleft =0;
unsigned int distanceleft =0;
unsigned int impulseTimeright=0;
unsigned int distanceright =0;
void loop()
{
bool newdata = false;
unsigned long start = millis();
if (mySerial.available())
{
char c = mySerial.read();
if (gps.encode(c))
{
newdata = true;
}
}
if (newdata) // <<-- removed: '= true'
{ //если спутники доступны
workonspeed(); //запуск программы чтения скорости
}
if (!newdata) // <<-- replaced: '(newdata) = false'
{ //если спутники недоступны, движение в тоннеле например
sonarleft (); //запуск программы левого сонара
sonarright ();
}
} // <<-- inserted missing close brace '}'
void workonspeed()
{
if (gps.f_speed_kmph()>10)
{ //если скорость по спутнику более 10кмч
sonarleft (); //запуск программы левого сонара
sonarright ();
}
}
void sonarleft ()
{ //левый сонар, чтение дистанции
digitalWrite(lefttrig, HIGH);
delayMicroseconds(10); // равный 10 микросекундам
digitalWrite(lefttrig, LOW);
impulseTimeleft=pulseIn(leftecho, HIGH); // Замеряем длину импульса
distanceleft=impulseTimeleft/58; // Пересчитываем в сантиметры
if (distanceleft<=150)
{
digitalWrite(leftred, HIGH) ; // red left led on
delay(2000);
}
else
{
digitalWrite(leftred, LOW) ; // red left led off
}
if ((distanceleft>=150) && (distanceleft<350 ))
{
digitalWrite(leftred, HIGH) ; // red left led on
digitalWrite(leftgreen, HIGH) ; // green left led on
}
else
{
digitalWrite(leftgreen, LOW) ; // green left led off
}
delay(100);
}
void sonarright()
{ //правый сонар, чтение данных
digitalWrite(righttrig, HIGH);
delayMicroseconds(10); // равный 10 микросекундам
digitalWrite(righttrig, LOW);// Отключаем
impulseTimeright=pulseIn(rightecho, HIGH); // Замеряем длину импульса
distanceright=impulseTimeright/58; // Пересчитываем в сантиметры
if (distanceright<=150) // right distance closer 60 cm
{
digitalWrite(rightred, HIGH) ; // red right led on
delay(2000);
}
else
{
digitalWrite(rightred, LOW) ; // red right led on
}
if ((distanceright>=150) && (distanceright<350 ))
{
digitalWrite(rightred, HIGH) ; // red right led on
digitalWrite(rightgreen, HIGH) ; // green right led on
}
else
{
digitalWrite(rightgreen, LOW) ; // green right led on
}
delay(100);
}
In this guide, we will discuss the ‘expected primary-expression before ‘)’ token’ error that developers often encounter during their coding journey. We will provide valuable insights and a step-by-step solution to help you understand and fix this error.
- Understanding the Error
- Common Causes of the Error
- Step-by-Step Solution
- FAQs
- Related Links
Understanding the Error
The ‘expected primary-expression before ‘)’ token’ error is a syntax error that occurs when a compiler is unable to parse an expression as expected. This usually happens when there is a missing, misplaced, or extraneous character in the code, causing the compiler to interpret the expression incorrectly.
This error is common in C, C++, and other programming languages that use similar syntax. It can cause your program to fail compilation and prevent it from running until the issue is resolved.
Common Causes of the Error
Here are some common causes of the ‘expected primary-expression before ‘)’ token’ error:
- Missing or misplaced parentheses, brackets, or braces
- Incorrect use of operators (e.g., using assignment operator ‘=’ instead of comparison operator ‘==’)
- Missing or extra semicolons, commas, or other punctuation marks
- Incorrectly nested code blocks or control structures
- Misspelled or misused variable or function names
Step-by-Step Solution
To solve the ‘expected primary-expression before ‘)’ token’ error, follow these steps:
Identify the line of code causing the error: The compiler will usually point out the line of code that caused the error. Carefully examine the line and the surrounding code to look for any syntax issues.
Check for missing or misplaced parentheses, brackets, or braces: Ensure that all opening and closing parentheses, brackets, and braces are correctly placed and matched. Also, make sure that you are not missing any required parentheses, brackets, or braces.
Verify the correct use of operators: Double-check your use of operators, ensuring that you are using the correct operators for the intended operation. For example, ensure that you are using the comparison operator ‘==’ instead of the assignment operator ‘=’ when comparing two values.
Look for missing or extra semicolons, commas, or other punctuation marks: Ensure that you have not missed any required semicolons or commas, and that you have not added any unnecessary punctuation marks.
Check for incorrectly nested code blocks or control structures: Make sure that all code blocks and control structures are correctly nested and that there are no misplaced opening or closing braces.
Review variable and function names: Double-check your variable and function names for spelling errors or incorrect usage. Ensure that you are using the right names for the intended variables or functions.
- Recompile and test: After making the necessary corrections, recompile your code and test it to ensure that the error has been resolved.
FAQs
Why does the ‘expected primary-expression before ‘)’ token’ error occur?
This error occurs when a compiler is unable to parse an expression as expected, usually due to a syntax issue such as missing, misplaced, or extraneous characters in the code.
How can I prevent this error from occurring in my code?
To prevent this error, always double-check your code for proper syntax, including correct use of parentheses, brackets, braces, operators, punctuation marks, and variable/function names.
Can this error occur in languages other than C or C++?
Yes, this error can occur in other programming languages that use similar syntax, such as Java, C#, and others.
What is the best way to debug this error?
The best way to debug this error is to carefully examine the line of code causing the error, as well as the surrounding code, to identify any syntax issues. Then, apply the step-by-step solution provided in this guide to resolve the error.
Is this error a runtime or compile-time error?
The ‘expected primary-expression before ‘)’ token’ error is a compile-time error, as it prevents your program from compiling and running until the issue is resolved.
- Cplusplus.com: Syntax errors
- Stack Overflow: Expected primary-expression before ‘)’ token
- GeeksforGeeks: Common Syntax Errors in C/C++
“Expected primary-expression before ‘some‘ token” is one of the most common errors that you can experience in Arduino code. Arduino code is written in C++ with few additions here and there, so it is a C++ syntax error. There are multiple versions of this error, depends on what is it that you messed up. Some are easy to fix, some not so much.
Most of the times (but not always), the error occurs because you have missed something or put it at the wrong place. Be it a semicolon, a bracket or something else. It can be fixed by figuring out what is that you missed/misplaced and placing it at the right position. Let us walk through multiple versions of the error and how to fix them one by one.
We all like building things, don’t we? Arduino gives us the opportunity to do amazing things with electronics with simply a little bit of code. It is an open-source electronics platform. It is based on hardware and software which are easy to learn and use. If I were to explain in simple language what Arduino does – it takes an input from the user in different forms such as touch or light and turns it into an output such as running a motor. Actually, you can even post tweets on Twitter with Arduino.
I’ll walk you through multiple examples of where the error can occur and how to possibly fix it. The codes that I use as examples in this article are codes that people posted on forums asking for a solution, so all credits of the code go to them. Let’s begin.
Type 1: Expected primary-expression before ‘}’ token
This error occurs when when the opening curly brackets ‘{‘ are not properly followed by the closing curly bracket ‘}’. To fix this, what you have to do is: check if all of your opening and closing curly brackets match properly. Also, check if you are missing any curly brackets. There isn’t much to this, so I’ll move on to the other types.
Type 2: Expected primary expression before ‘)’ token
Example 1: All credits to this thread. Throughout all of my examples, I will highlight the line which is causing the issue with red.
#include <Adafruit_NeoPixel.h>
#include <BlynkSimpleEsp8266.h>
#include <ESP8266WiFi.h>
#define PIN D1
#define NUMPIXELS 597
int red = 0;
int green = 0;
int blue = 0;
int game = 0;
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
///////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup() {
Blynk.begin("d410a13b55560fbdfb3df5fe2a2ff5", "8", "12345670");
pixels.begin();
pixels.show();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
BLYNK_WRITE(V1) {
game = 1;
int R = param[0].asInt();
int G = param[1].asInt();
int B = param[2].asInt();
setSome(R, G, B);
}
BLYNK_WRITE(V2) {
if (param.asInt()==1) {
game = 2;
rainbow(uint8_t); // Rainbow
}
else {
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
void loop()
{
Blynk.run();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
void rainbow(uint8_t wait) {
uint16_t i, j;
for(j=0; j<256; j++) {
for(i=0; i<NUMPIXELS; i++) {
pixels.setPixelColor(i, Wheel((i+j) & 255));
}
pixels.show();
delay(wait);
}
// delay(1);
}
uint32_t Wheel(byte WheelPos) {
WheelPos = 255 - WheelPos;
if(WheelPos < 85) {
return pixels.Color(255 - WheelPos * 3, 0, WheelPos * 3);
}
if(WheelPos < 170) {
WheelPos -= 85;
return pixels.Color(0, WheelPos * 3, 255 - WheelPos * 3);
}
WheelPos -= 170;
return pixels.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}BLYNK_WRITE(V3) {
if (param.asInt()) {
game = 3;
setAll(125, 47, 0); //candle
}
else {
}
}
BLYNK_WRITE(V4) {
game = 4;
int Bright = param.asInt();
pixels.setBrightness(Bright);
pixels.show();
}
BLYNK_WRITE(V5) {
if (param.asInt()) {
game = 5;
setAll(85, 0, 255);
}
else {
}
}
BLYNK_WRITE(V6) {
if (param.asInt()) {
game = 6;
oFF(red, green, blue);
// fullOff();
}
else {
}
}
BLYNK_WRITE(V7) {
if (param.asInt()) {
game = 7;
setAll(255, 0, 85);
}
else {
}
}
BLYNK_WRITE(V8) {
if (param.asInt()) {
game = 8;
setAll(90, 90, 90);
}
else {
}
}
BLYNK_WRITE(V9) {
if (param.asInt()) {
game = 9;
setAll(255, 130, 130);
}
else {
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
void oFF(byte r, byte g, byte b) {
if (game == 1) {
offsome(r, g, b);
}
else if (game == 2) {
offall(r, g, b);
}
else if (game == 3) {
offall(r, g, b);
}
else if (game == 4) {
offall(r, g, b);
}
else if (game == 5) {
offall(r, g, b);
}
else if (game == 6) {
offall(r, g, b);
}
else if (game == 7) {
offall(r, g, b);
}
else if (game == 8) {
offall(r, g, b);
}
else if (game == 9) {
offall(r, g, b);
}
}
void offall(byte r, byte g, byte b) {
uint32_t x = r, y = g, z = b;
for (x; x > 0; x--) {
if( y > 0 )
y--;
if( z > 0 )
z--;
for(int i = 0; i < NUMPIXELS; i++ ) {
pixels.setPixelColor(i, pixels.Color(x, y, z));
}
pixels.show();
delay(0);
}
//delay(0);
}
void offsome(byte r, byte g, byte b) {
uint32_t x = r, y = g, z = b;
for (x; x > 0; x--) {
if( y > 0 )
y--;
if( z > 0 )
z--;
for(int i = 87; i < 214; i++ ) {
pixels.setPixelColor(i, pixels.Color(x, y, z));
}
for(int i = 385; i < 510; i++ ) {
pixels.setPixelColor(i, pixels.Color(x, y, z));
}
pixels.show();
delay(0);
}
}
void setAll(byte r, byte g, byte b) {
uint16_t x = 0, y = 0, z = 0;
for (x; x < r; x++) {
if( y < g )
y++;
if( z < b )
z++;
for(int i = 0; i < NUMPIXELS; i++ ) {
pixels.setPixelColor(i, pixels.Color(x, y, z));
}
pixels.show();
red = r;
green = g;
blue = b;
delay(0);
}
//delay(0);
}
void setSome(byte r, byte g, byte b) {
uint16_t x = 0, y = 0, z = 0;
for (x; x < r; x++) {
if( y < g )
y++;
if( z < b )
z++;
for(int i = 86; i < 212; i++ ) {
pixels.setPixelColor(i, pixels.Color(x, y, z));
}
for(int i = 385; i < 512; i++ ) {
pixels.setPixelColor(i, pixels.Color(x, y, z));
}
pixels.show();
red = r;
green = g;
blue = b;
delay(0);
}
//delay(0);
}
void fullOff() {
for(int i = 0; i < NUMPIXELS; i++ ) {
pixels.setPixelColor(i, pixels.Color(0, 0, 0));
}
pixels.show();
}
Solution 1:
The error occurs in this code because the rainbow function is supposed to have a variable as its argument, however the argument given here is ‘uint8_t’ which is not a variable.
BLYNK_WRITE(V2) {
if (param.asInt()==1) {
game = 2;
rainbow(uint8_t); // Rainbow
}
else {
}
}
Here all you have to do is define uint8_t as a variable first and assign it a value. The code will work after that.
Type 3: Expected primary-expression before ‘enum’
Example 1: All credits to this thread.
#include <iostream>
using namespace std;
int main()
{
enum userchoice
{
Toyota = 1,
Lamborghini,
Ferrari,
Holden,
Range Rover
};
enum quizlevels
{
Hardquestions = 1,
Mediumquestions,
Easyquestions
};
return 0;
}
Solution 1:
The “expected primary-expression before ‘enum’ ” error occurs here because the enum here has been defined inside a method, which is incorrect. The corrected code is:
#include <iostream>
using namespace std;
enum userchoice
{
Toyota = 1,
Lamborghini,
Ferrari,
Holden,
RangeRover
};
enum quizlevels
{
HardQuestions = 1,
MediumQuestions,
EasyQuestions
};
int main()
{
return 0;
}
Note: Another mistake has been fixed in this code i.e. the space in “Range Rover” variable. Variable names cannot contain spaces.
Type 4: Expected primary expression before ‘.’
Example 1: All credits go to this thread.
#include <iostream>
using std::cout;
using std::endl;
class square {
public:
double length, width;
square(double length, double width);
square();
~square();
double perimeter();
};
double square::perimeter() {
return 2*square.length + 2*square.width;
}
int main() {
square sq(4.0, 4.0);
cout << sq.perimeter() << endl;
return 0;
}
Solution 1: Here the error occurs because “square” is being used as an object, which it is not. Square is a type, and the corrected code is given below.
#include <iostream>
using std::cout;
using std::endl;
class square {
public:
double length, width;
square(double length, double width);
square();
~square();
double perimeter();
};
double square::perimeter() {
return 2*length + 2*width;
}
int main() {
square sq(4.0, 4.0);
cout << sq.perimeter() << endl;
return 0;
}
Type 5: Expected primary-expression before ‘word’
Example 1: All credits go to this thread.
#include <iostream>
#include <string>
using namespace std;
string userInput();
int wordLengthFunction(string word);
int permutation(int wordLength);
int main()
{
string word = userInput();
int wordLength = wordLengthFunction(string word);
cout << word << " has " << permutation(wordLength) << " permutations." << endl;
return 0;
}
string userInput()
{
string word;
cout << "Please enter a word: ";
cin >> word;
return word;
}
int wordLengthFunction(string word)
{
int wordLength;
wordLength = word.length();
return wordLength;
}
int permutation(int wordLength)
{
if (wordLength == 1)
{
return wordLength;
}
else
{
return wordLength * permutation(wordLength - 1);
}
}
Solution 1:
Here, they are incorrectly using string inside wordLengthFunction().
Fixing it is simple, simply replace
int wordLength = wordLengthFunction(string word);
by
int wordLength = wordLengthFunction(word);
Type 6: Expected primary-expression before ‘else’
Example 1: All credit goes to this thread.
// Items for sale:
// Gizmos - Product number 0-999
// Widgets - Product number 1000-1999
// doohickeys - Product number 2000-2999
// thingamajigs - Product number 3000-3999
// Product number >3999 = Invalid Item
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
float ProdNumb; // Product Number
double PrG; // Product Number for Gizmo
double NG; // Number of items
double PG; // Price of Item
double PrW; // Product Number for Widgets
double NW; // Number of items
double PW; // Price of Item
double PrD; // Product Number for Doohickeys
double ND ; // Number of items
double PD ; // Price of Item
double PrT; // Product Number for Thingamajigs
double NT; // Number of items
double PT; // Price of Item
double PrI; //Product Number for Invalid (> 3999)
double NI; // Number of items
double PI; // Price of Item
double total = 0;
int main ()
{
cout << "Enter the product number of the item sold: ";
cin >> ProdNumb;
while (ProdNumb != -1)
{
if (ProdNumb >= 0 && ProdNumb <= 999)
{
ProdNumb == PrG;
cout << "Enter the number of items sold: ";
cin >> NG;
cout << "Enter the price of one of the items sold: ";
cin >> PG;
}
cout << "Enter the product number of the item sold: ";
cin >> ProdNumb;
else (ProdNumb >= 1000 && ProdNumb <= 1999)
{
ProdNumb == PrW;
cout << "Enter the number of items sold: ";
cin >> NW;
cout << "Enter the price of one of the items sold: ";
cin >> PW;
cout << "Enter the product number of the item sold: ";
cin >> ProdNumb;
}
else (ProdNumb >= 2000 && ProdNumb <= 2999)
{
ProdNumb == PrD;
cout << "Enter the number of items sold: ";
cin >> ND;
cout << "Enter the price of one of the items sold: ";
cin >> PD;
cout << "Enter the product number of the item sold: ";
cin >> ProdNumb;
}
else (ProdNumb >= 3000 && ProdNumb <= 3999)
{
ProdNumb == PrT;
cout << "Enter the number of items sold: ";
cin >> NT;
cout << "Enter the price of one of the items sold: ";
cin >> PT;
cout << "Enter the product number of the item sold: ";
cin >> ProdNumb;
}
else (ProdNumb <= -2 && ProdNumb == 0 && ProdNumb >= 4000)
{
ProdNumb == PrI;
cout << "Enter the number of items sold: ";
cin >> NI;
cout << "Enter the price of one of the items sold: ";
cin >> PI;
cout << "Enter the product number of the item sold: ";
cin >> ProdNumb;
}
}
cout << "***** Product Sales Summary *****";
cout << "n";
cout << "n";
cout << "Gizmo Count: ";
total += NG;
cout << NG;
cout << "n";
cout << "Gizmo Sales Total: ";
cout << (NG)*(PG);
cout << "n";
cout << "n";
cout << "Widget Count: ";
total += NW;
cout << NW;
cout << "n";
cout << "Widget Sales Total: ";
cout << (NW)*(PW);
cout << "n";
cout << "n";
cout << "Dookickey Count: ";
total += ND;
cout << ND;
cout << "n";
cout << "Doohickey Sales Total: ";
cout << (ND)*(PD);
cout << "n";
cout << "n";
cout << "Thingamajig Count: ";
total += NT;
cout << NT;
cout << "n";
cout << "Thingamajig Sales Total: ";
cout << (NT)*(PT);
cout << "n";
cout << "n";
cout << "Invalid Sales: ";
total += NI;
cout << NI;
return 0;
}
Solution 1:
This code is not correct because after the if statement is closed with ‘}’ in this code, there are two statements before the else statement starts. There must not be any statements between the closing curly bracket ‘}’ of if statement and the else statement. It can be fixed by simply removing the part that I have marked in red.
Conclusion
And that’s it, I hope you were able to fix the expected primary-expression before error. This article wasn’t easy to write – I’m in no way an expert in C++, but I do know it to a decent level. I couldn’t find any articles related to fixing this error on the internet so I thought I’d write one myself. Answers that I read in forums helped me immensely while researching for this article and I’m thankful to the amazing community of programmers that we have built! If you would like to ask me anything, suggest any changes to this article or simply would like to write for us/collaborate with us, visit our Contact page. Thank you for reading, I hope you have an amazing day.
Also, tell me which one of the 6 types were you experiencing in the comments below.
I know this is a common question but the truth is every code is different. Sometimes it’s hard to apply the concept to your code, it does not work. So please help me. What is wrong with this code? I got it from GitHub. I’m trying to compile it first before I can do a little modification, it sends temp and humidity data to ThingSpeak cloud servers.
#include <DHT.h> // Including library for dht
#include <ESP8266WiFi.h>
String api_key = "YOUR API KEY"; // Enter your Write API key from ThingSpeak
const char *ssid = "YOUR WIFI SSID"; // replace with your wifi ssid and wpa2 key
const char *pass = "YOUR WIFI PASSWORD";
const char* server = "api.thingspeak.com";
#define DHTPIN 1 // pin where the dht11 is connected
DHT dht;
WiFiClient client;
void setup() {
Serial.begin(115200);
delay(10);
pinMode(2, OUTPUT);
digitalWrite(2, 0);
Serial.println("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop() {
int chk = DHT.read(DHTPIN);
float hum = DHT.humidity;
float temp = DHT.temperature;
if (isnan(hum) || isnan(temp)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
if (client.connect(server, 80)) {
// "184.106.153.149" or api.thingspeak.com
String data_to_send = api_key;
data_to_send += "&field1=";
data_to_send += hum;
data_to_send += "&field2=";
data_to_send += temp;
data_to_send += "rnrn";
client.print("POST /update HTTP/1.1n");
client.print("Host: api.thingspeak.comn");
client.print("Connection: closen");
client.print("X-THINGSPEAKAPIKEY: " + api_key + "n");
client.print("Content-Type: application/x-www-form-
urlencodedn");
client.print("Content-Length: ");
client.print(data_to_send.length());
client.print("nn");
client.print(data_to_send);
delay(1000);
Serial.print("Temperature: ");
Serial.print(temp);
Serial.print(" degrees Celcius, Humidity: ");
Serial.print(hum);
Serial.println("%. Send to Thingspeak.");
}
client.stop();
Serial.println("Waiting...");
// ThingSpeak needs minimum 15 sec delay between updates, I've set it to 30 seconds
delay(10000);
}
When I compile I get this error,
Arduino: 1.8.10 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E
Module), 80 MHz, Flash,
Legacy (new can return nullptr), All SSL ciphers (most
compatible),
4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200"
C:UsersAgent 96Desktopthingspeakthingspeak.ino: In function 'void loop()':
thingspeak:37:20: error: expected primary-expression before '.' token
int chk = DHT.read(DHTPIN);
^
thingspeak:38:22: error: expected primary-expression before '.' token
float hum = DHT.humidity;
^
thingspeak:39:23: error: expected primary-expression before '.' token
float temp = DHT.temperature;
^
Multiple libraries were found for "DHT.h"
Used: C:UsersAgent
Not used: C:UsersAgent
Multiple libraries were found for "ESP8266WiFi.h"
Used: C:UsersAgent
exit status 1
expected primary-expression before '.' token
This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
Please help, I’m kind of a beginner.
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
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
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
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.
