1
You did not define your Constructor
and Destructor
You declared them both in your set_char.hpp
set_char(unsigned char *zbior[]);
~set_char(unsigned char *zbior[]);
However in set_char.cpp
you re-declare them again without a return type. Defining a Constructor
and Destructor
outside of a class
is illegal. Your compiler thinks they are functions
and searches for a return type.
2
a Destructor
may not have any arguments.
3
If you define an array as an argument in a Function
or a Constructor
or Destructor
with brackets ‘[]’, it may not be of variable length, thus it must be defined. If it is intended to be of variable length, it must be left out.
4
You are calling the constructor in a bad way using:
new set_char(unsigned char *zbior[]);
You already declared what arguments it takes, so hand it the arguments. A null pointer
, for example.
The correct way to do it in set_char.hpp
:
set_char(unsigned char *);
~set_char();
The correct way to do it in set_char.cpp
:
set_char::set_char(unsigned char *zbior)
{
//Your definition
}
set_char::~set_char();
{
//Your definition
}
The correct way to do it in head.cpp
:
set_char *z1 = new set_char(0x0);
Also side-note, usually using the define
macro to define constants, is a C
way. In C++
it is usually done with:
static const size_t ROZMIAR_MAX 256;
Second side-note. It is considered ‘neater’ code if you have your constants/functions and whatnot defined inside a namespace
- Forum
- Beginners
- expected primary-expression before ‘un
expected primary-expression before ‘unsigned’
Greetings, I’m new to C++ programming and have been studying it for a couple of days. I have run into a few problems, like all beginners, but have always been able to figure them out until now.The program I am stuck on is as follows:
|
|
and one of the errors i get is the «Exprected unqualified-id before ‘unsigned’
main.cc:24:27: error: expected primary-expression before ‘unsigned’
i copied this code from a booklet i found and i’m guessing there could be something wrong with my compiler because i copied it exactly the same.
The code is supposed to map the address from a list with the parameters of a N-dimensional array pointing to a particular subindex.
could someone assist me on solving this error please?
I found that GCC prints a similar error, although it is on lines 1, 2, and 7, not 24, of the code you posted. Please post the same code you’re compiling next time!
And that is not the first error message printed; the first one is
test.cc:1:21: error: ‘lista’ was not declared in this scope
If you fix it, then the message «expected primary-expression before ‘unsigned’» will disappear as well.
It should be
list
not lista
this is the code i’m compiling!
i had the terminal so small that i didn’t realize there was another error line before the one i posted.
I really appreciate your help and your rapid response.
Could you give me a hint on how to declare ‘lista’ ?
i’m not really a very skilled programmer and i’m not really used to this language neither hehe
is lista a class object? or is it supposed to be list? Also line 7 you should not name the «object» the same as the «variable name» that is like doing int int.
Last edited on
lista is a class object
you declare lista like
|
|
You were trying to use lista as a vector of int pointers.
like this
|
|
*edit
You can also make a vector of objects like
|
|
Last edited on
Topic archived. No new replies allowed.
The expected primary expression before occurs due to syntax errors. It usually has a character or a keyword at the end that clarifies the cause. Here you’ll get access to the most common syntax mistakes that throw the same error.
Continue reading to see where you might be getting wrong and how you can solve the issue.
Contents
- Why Does the Expected Primary Expression Before Occur?
- – You Are Specifying the Data Type With Function Argument
- – The Wrong Type of Arguments
- – Issue With the Curly Braces Resulting in Expected Primary Expression Before }
- – The Parenthesis Following the If Statement Don’t Contain an Expression
- How To Fix the Given Error?
- – Remove the Data Type That Precedes the Function Argument
- – Pass the Arguments of the Expected Data Type
- – Ensure The Equal Number of Opening and Closing Curly Brackets
- – Add an Expression in the If Statement Parenthesis
- FAQ
- – What Does It Mean When the Error Says “Expected Primary Expression Before Int” in C?
- – What Is a Primary Expression in C Language?
- – What Are the Types of Expressions?
- Conclusion
Why Does the Expected Primary Expression Before Occur?
The expected primary expression before error occurs when your code doesn’t follow the correct syntax. The mistakes pointed out below are the ones that often take place when you are new to programming. However, a programmer in hurry might make the same mistakes.
So, here you go:
– You Are Specifying the Data Type With Function Argument
If your function call contains the data type along with the argument, then you’ll get an error.
Here is the problematic function call:
int addFunction(int num1, int num2)
{
int sum;
sum = num1 + num2;
return sum;
}
int main()
{
int result = addFunction(int 20, int 30);
}
– The Wrong Type of Arguments
Passing the wrong types of arguments can result in the same error. You can not pass a string to a function that accepts an argument of int data type.
int main()
{
int result = addFunction(string “cat”, string “kitten”);
}
– Issue With the Curly Braces Resulting in Expected Primary Expression Before }
Missing a curly bracket or adding an extra curly bracket usually results in the mentioned error.
– The Parenthesis Following the If Statement Don’t Contain an Expression
If the parenthesis in front of the if statement doesn’t contain an expression or the result of an expression, then the code won’t run properly. Consequently, you’ll get the stated error.
How To Fix the Given Error?
You can fix the “expected primary-expression before” error by using the solutions given below:
– Remove the Data Type That Precedes the Function Argument
Remove the data type from the parenthesis while calling a function to solve the error. Here is the correct way to call a function:
int main()
{
int result = addFunction(30, 90);
}
– Pass the Arguments of the Expected Data Type
Double-check the function definition and pass the arguments of the type that matches the data type of the parameters. It will ensure that you pass the correct arguments and kick away the error.
– Ensure The Equal Number of Opening and Closing Curly Brackets
Your program must contain an equal number of opening and closing curly brackets. Begin with carefully observing your code to see where you are doing the mistake.
– Add an Expression in the If Statement Parenthesis
The data inside the parenthesis following the if statement should be either an expression or the result of an expression. Even adding either true or false will solve the issue and eliminate the error.
FAQ
You can view latest topics and suggested topics that’ll help you as a new programmer.
– What Does It Mean When the Error Says “Expected Primary Expression Before Int” in C?
The “expected primary expression before int” error means that you are trying to declare a variable of int data type in the wrong location. It mostly happens when you forget to terminate the previous statement and proceed with declaring another variable.
– What Is a Primary Expression in C Language?
A primary expression is the basic element of a complex expression. The identifiers, literals, constants, names, etc are considered primary expressions in the C programming language.
– What Are the Types of Expressions?
The different types of expressions include arithmetic, character, and logical or relational expressions. An arithmetic expression returns an arithmetic value. A character expression gives back a character value. Similarly, a logical value will be the output of a logical or relational expression.
Conclusion
The above error revolves around syntax mistakes and can be solved easily with a little code investigation. The noteworthy points depicting the solutions have been written below to help you out in removing the error:
- Never mention the data type of parameters while calling a function
- Ensure that you pass the correct type of arguments to the given function
- You should not miss a curly bracket or add an extra one
- The if statement should always be used with the expressions, expression results, true, or false
The more you learn the syntax and practice coding, the more easily you’ll be able to solve the error.
- Author
- Recent Posts
Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.
prutkin41 0 / 0 / 0 Регистрация: 20.07.2012 Сообщений: 4 |
||||
1 |
||||
20.07.2012, 07:23. Показов 32218. Ответов 7 Метки нет (Все метки)
код
__________________
0 |
25 / 25 / 5 Регистрация: 21.04.2011 Сообщений: 141 |
|
20.07.2012, 08:18 |
2 |
Функция how_big_and_litle не возвращает значение, а в заголовке она определена как возвращающая значение. Нужно либо в функцию return 0; поставить либо в определении функции вместо int поставить void
0 |
prutkin41 0 / 0 / 0 Регистрация: 20.07.2012 Сообщений: 4 |
||||
20.07.2012, 08:29 [ТС] |
3 |
|||
так не работает
0 |
xADMIRALx 69 / 63 / 5 Регистрация: 09.06.2012 Сообщений: 291 |
||||
20.07.2012, 09:10 |
4 |
|||
Сначала объявляем прототип функции,а затем реализовываем ее Читайте литературу,слишком наивные вопросы
0 |
Infinity3000 1066 / 583 / 87 Регистрация: 03.12.2009 Сообщений: 1,255 |
||||
20.07.2012, 09:52 |
5 |
|||
Сначала объявляем прототип функции,а затем реализовываем ее Читайте литературу,слишком наивные вопросы прототип функции не обязательно обьявлять если функция реализованая до первого ее вызова!
1 |
0 / 0 / 0 Регистрация: 20.07.2012 Сообщений: 4 |
|
20.07.2012, 12:20 [ТС] |
6 |
почему со «smal» компилируется, а с изначальным «small» -нет?
0 |
Schizorb 512 / 464 / 81 Регистрация: 07.04.2012 Сообщений: 869 Записей в блоге: 1 |
||||
20.07.2012, 12:36 |
7 |
|||
prutkin41, не подключай <windows.h>, в нем опеределена
Добавлено через 1 минуту
1 |
0 / 0 / 0 Регистрация: 20.07.2012 Сообщений: 4 |
|
20.07.2012, 14:04 [ТС] |
8 |
почему возникает переполнение? извиняюсь за нубские вопросы — надо разобраться
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
20.07.2012, 14:04 |
Помогаю со студенческими работами здесь Ошибка «expected primary-expression before ‘>’ token» Перегрузка оператора <<: «expected primary-expression» Исправить ошибку «expected primary-expression» expected primary-expression before «bre» ; expected `;’ before «bre» ; `bre’ undeclared (first use this function) expected primary-expression before «else» В зависимости от времени года «весна», «лето», «осень», «зима» определить погоду «тепло», «жарко», «холодно», «очень холодно» Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 8 |
statement result += unsigned int(1) < < i;
can be compiled and run locally, but a compilation error appears after uploading to LeetCode: expected primary-expression before ‘unsigned’.
analysis:
statement is too complex, the compiler on LeetCode can not fully compile, need to add the basic expression.
solution:
1 for unsigned int
add parentheses: (unsigned int)
.
2 add intermediate variable unsigned int one = 1; result += one < < I .
Read More:
- JAVA lambda Syntax error on tokens, Expression expected instead
- C code compilation_ Error: expected expression before ‘Int’
- Syntax Error: SassError: Invalid CSS after “…-height: #{math“: expected expression (e.g. 1px, bold
- error Expected an assignment or function call and instead saw an expression
- _ASSERTE((unsigned)(c + 1) <= 256);
- error C2057: expected constant expression (Can the size of an array in C language be defined when the program is running?)
- The solution of duplicate entry ‘for key’ primary ‘when inserting data in MySQL
- Txt import MySQL: error 1062 (23000): duplicate entry ‘0’ for key ‘primary’
- Duplicate entry ‘787192513’ for key ‘primary’
- Stm32f103c8t6 in keil compiler error: # 67: expected a “}” solution
- The reason and solution of the error of join function: sequence item 0: expected STR instance, int found
- C language error – [error] expected declaration or statemt at end of input— solution.
- [reprint and save] MySQL does not set the primary key and uses the self growing ID method
- MySQL creates tables and sets auto increment of primary keys
- docker apache php-fpm AH01071: Got error ‘Primary script unknownn’
- Failed to notify ProjectEvaluationListener.afterEvaluate(), but primary configuration failure takes
- How to Fix Warning: Statement lambda can be replaced with expression lambda
- Error Code: 1055. Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated
- Solve the problem that vscode cannot convert the easy less plug-in to the less expression value
- [Solved] Unity Error: Assertion failed on expression: ‘m_ErrorCode == MDB_MAP_RESIZED
Вы не даете нам достаточно контекста, чтобы понять, что вы пытаетесь сделать.
Я собираюсь предположить, что вы хотите вызвать функцию alarm
с аргументом 0. Согласно странице man (введите man alarm
или man 2 alarm
или следуйте по этой ссылке), alarm(0)
отменит любой существующий сигнал тревоги без установив новый.
В моей системе (Ubuntu, Linux, то есть Unix-подобная система) следующие компиляции, ссылки и выполнение без ошибок:
#include <unistd.h>
int main(void) {
alarm(0);
return 0;
}
Я сохранил программу в файле cc
, и я скомпилировал и связал ее со следующей командой:
gcc c.c -o c
и выполнил его с:
./c
Реализация функции alarm
происходит в стандартной библиотеке C, которая по умолчанию связана. Это может быть или не быть в вашей системе, но если это Linux или какая-то другая Unix-подобная система, возможно, это так.
(Это не очень полезная программа, но это может быть отправной точкой для чего-то полезного.
РЕДАКТИРОВАТЬ :
Теперь я вижу, что вы используете Windows. Функция alarm()
определяется стандартом POSIX и (в основном) относится к Unix-подобным системам. Windows, вероятно, не предоставляет его по умолчанию. Существуют Unix-подобные уровни эмуляции, которые запускаются под Windows, например Cygwin.
Но если вы хотите разработать код под Windows, вы можете подумать об избежании несанкционированных конструкций, которые Windows не поддерживает (напрямую).
Почему вы хотите вызвать alarm()
? У вас есть требование делать то, что делает эта конкретная функция, или вы просто пытаетесь изучить основы?
“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.
Table of Contents
- How to fix “Expected Primary-Expression Before” error?
- Type 1: Expected primary-expression before ‘}’ token
- Type 2: Expected primary expression before ‘)’ token
- Type 3: Expected primary-expression before ‘enum’
- Type 4: Expected primary expression before ‘.’
- Type 5: Expected primary-expression before ‘word’
- Type 6: Expected primary-expression before ‘else’
- Conclusion
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.
Я не понимаю, почему следующий код не компилируется при использовании приведения типа конструктора:
template<typename T> void foo(const T& t){}
int main(){
foo(unsigned char(0));
}
Ошибки:
error: expected primary-expression before ‘unsigned’
для GCC.error: expected '(' for function-style cast or type construction
для лязга
Однако эти три синтаксиса верны:
template<typename T> void foo(const T& t){}
int main(){
// c-style cast
foo((unsigned char)0);
// without unsigned
foo(char(0));
// aliased unsigned char
typedef unsigned char uchar;
foo(uchar(0));
}
Таким образом, пространство в типе, очевидно, здесь виновато.
Я думал, что это может быть как-то связано с нашим старым другом самый неприятный разбор, поэтому я попробовал единый синтаксис инициализации, который должен избавиться от такого рода неясностей, но не повезло
template<typename T> void foo(const T& t){}
int main(){
foo(unsigned char{0});
}
Но до сих пор:
error: expected primary-expression before ‘unsigned’
для GCC.error: expected '(' for function-style cast or type construction
для лязга
Итак, мой вопрос: почему нельзя использовать тип, содержащий пробел, в приведениях в стиле функции? Это не выглядит двусмысленным для меня.
нотаЯ знаю, что могу написать foo<unsigned char>(0)
, но это не отвечает на вопрос;)
19
Решение
[C++11: 5.2.3/1]:
простой тип спецификатор (7.1.6.2) или имяТипа спецификатор (14.6) с последующим в скобках список_выражений создает значение указанного типа с учетом списка выражений. [..]
Изучая грамматику, мы видим, что единственный способ получить unsigned char
от простой тип спецификатор производство путем объединения двух из них.
В качестве доказательства опровержения слухов о том, что таблица 10 утверждает обратное, которое я, возможно, сам начал некоторое время назад (: P), заголовок таблицы говорит «спецификатор (ы)» (обратите внимание на необязательное множественное число) и ссылается на проход:
[C++11: 5.2.3/2]:
[..] В таблице 10 приведены действительные комбинации из простой типа спецификаторы и типы, которые они указывают. (акцент мой)
Теперь, объединяя простой типа спецификаторы допускается в некоторых случаях:
[C++11: 7.1.6.2/3]:
Когда несколько простой типа спецификаторы разрешены, они могут свободно смешиваться с другими Децл-спецификаторы в любом порядке. [..]
… но нет никаких признаков того, что это имеет место с функциональной нотацией, которая ясно заявляет « простой тип спецификатор» — единственное число.
Поэтому GCC правильно, а Visual Studio неправильно.
Что касается Зачем это тот случай … ну, я не знаю. Я подозреваю, что мы могли бы придумать какой-то неоднозначный крайний случай, но Casey В комментариях ниже отмечается, что разрешение этого было бы несовместимо с синтаксисом вызова функции, поскольку в именах функций не должно быть пробелов.
16
Другие решения
|
|
|
информация о разделе
Данный раздел предназначается исключительно для обсуждения вопросов использования языка запросов SQL. Обсуждение общих вопросов, связанных с тематикой баз данных — обсуждаем в разделе «Базы данных: общие вопросы». Убедительная просьба — соблюдать «Правила форума» и не пренебрегать «Правильным оформлением своих тем». Прежде, чем создавать тему, имеет смысл заглянуть в раздел «Базы данных: FAQ», возможно там уже есть ответ. |
mysql C api при компиляции ошибка
- Подписаться на тему
- Сообщить другу
- Скачать/распечатать тему
|
|
Привет всем!
#include <stdio.h> #include <mysql.h> MYSQL *conn; /* pointer to connection handler */ int main ( int argc, char *argv[] ) { conn = mysql_init ( NULL ); mysql_real_connect ( conn, /* pointer to connection handler */ «localhost», /* host to connect to */ «user_name», /* user name */ «password», /* password */ «test», /* database to use */ 0, /* port (default 3306) */ NULL, /* socket or /var/lib/mysql.sock */ 0 ); /* flags (none) */ mysql_close ( conn ); return 0; } gcc a.c -o a.exe -Lc:mysqlbin -Ic:mysqlinclude И в итоги получаю такое сообщение In file included from include/mysql.h:72, Плз, почему возникает такая ошибка |
Шадофф |
|
Странно, по указанным строкам в указанном файле нет вообще ни каких упоминаний про структуру SOCKET. Цитата Плз, почему возникает такая ошибка
Не находит описания SOCKET. #include <winsock.h> в исходнике явно есть. Сталбыть, компиль не видит winsock.h… |
Шадофф |
|
Немного подумав. Речь идёт вот об этом -> http://www.bloodshed.net/dev/devcpp.html Ктому же, хоть gcc.exe и в винде, он по идее, должен «понимать» где находится, но не худо было бы ему явно указать это. Хотя, если честно, то лучше прогуляться по ссылке выше, скачатьоттуда порядка 5 MB, потом налоить через менеджер пакетов обновления (mysql и postgres там есть) и забыть о проблемах. Добавлено 27.07.08, 06:19 Кстати, а точно библиотека mysql лежит в c:mysqlbin? |
itwork |
|
Цитата Шадофф @ 26.07.08, 20:03 Под вяндой лучше поставить себе «аналог» cygwin’а (в основе лежит mingw) — Dev-C++ т.е имели ввиду использовать mingw32-gcc!? mingw32-gcc aaa.c -o aaa.exe -Lc:mysqllibopt -Ic:mysqlinclude -DWIN32 -D_WINDOWS -no-cygwin результат тотже Сообщение отредактировано: itwork — 27.07.08, 09:01 |
Шадофф |
|
Цитата т.е имели ввиду использовать mingw32-gcc!? Угу. Он в Dev-C++ (в среду) встроенный. Это не сильно важно. Важнее другое — там все пути сразу подточены. В данном случае, по-моему, не находит заголовочный файл от win. Он вообще есть? Я имею ввиду winsock.h? |
itwork |
|
c:MinGWinclude |
itwork |
|
понял!!! это дело в mysql.h! вот токо как правильно mysql.h отредактировать Сообщение отредактировано: itwork — 27.07.08, 20:02 |
Шадофф |
|
Я то же. Блин, я тормоз. Понял это когда глянул свой проект примерно трёх-летней давности… Цитата это дело в mysql.h! Отчасти да. Короче, для решения всех проблем надо сделать следующее:
#include <my_global.h> #include <mysql.h>
Вот именно в таком порядке эти два файла должны быть прописаны в исходнике. В my_global.h прописаны «конвертации» для платформы винды. И, на винде, оно так и должно быть прописано. Кроме того, в проекте должны быть привязаны либы -lm -lwsock32 -luser32 -lgcc. Сообщение отредактировано: Шадофф — 28.07.08, 07:17 |
0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
0 пользователей:
- Предыдущая тема
- Базы данных: SQL
- Следующая тема
[ Script execution time: 0,0276 ] [ 15 queries used ] [ Generated: 9.02.23, 13:33 GMT ]