Main cpp expected primary expression before int

Компилатор, ошибка «expected primary-expression before «int» «

Исправить ошибку «expected primary-expression before ‘int'»
У меня есть простая функция в классе func1(int i) и я пытаюсь написать следующую функцию: void *.

Ошибка «expected primary-expression before ‘char'» при объявления переменной
#include <iostream> #include <cstring> #include <cstdio> using namespace std; void.

Ошибка expected primary-expression before «long»
#include<iostream> #include<cstdlib> #include<math.h> using namespace std; int main(void)

Функция how_big_and_litle не возвращает значение, а в заголовке она определена как возвращающая значение. Нужно либо в функцию return 0; поставить либо в определении функции вместо int поставить void

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
int show_big_and_litle(int a, int b, int c) { int small=a; int big=a; if(b>big) big=b; if(bsmall) small=b; if(c>big) big=c; if(csmall) small=c; cout<"Самое большое значение равно "; cout<"Самое маленькое значение равно "; return(0); } int main(void) { show_big_and_litle(1,2,3); show_big_and_litle(500,0,-500); show_big_and_litle(1001,1001,1001); system("pause"); }

Сначала объявляем прототип функции,а затем реализовываем ее Читайте литературу,слишком наивные вопросы

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
#include #include // для system using namespace std; void show_big_and_litle(int a, int b, int c); int main(void) { show_big_and_litle(1,2,3); show_big_and_litle(500,0,-500); show_big_and_litle(1001,1001,1001); system("pause"); } void show_big_and_litle(int a, int b, int c) { int small=a; int big=a; if(b>big) big=b; if(bsmall) small=b; if(c>big) big=c; if(csmall) small=c; cout<"Самое большое значение равно "; cout<"Самое маленькое значение равно "; }

Источник

C++ Error: Expected Primary Expression Before

While writing a code, a programmer may encounter some ambiguities. There are various types of errors like logical errors, compile-time errors, or syntax error. Logical errors are difficult to understand because it doesn’t show any error while syntax and compile time errors don’t even execute; they generate an error while the compilation of the code starts.

Today, we will discuss about a syntax error that may occur due to something missing in the code or something that is added to the code. The error that we are going to discuss is “expected primary expression”. This error mainly occurs when there is some missing keyword. To get to know this error, there is a keyword or character at the end which shows the reason for the error occurrence. When the syntax is not correctly followed by the coder, it does execute successfully. It displays the error which indicates the line where it is encountered.

The major reasons for the occurrence of the error are:

  • If the datatype of the argument is also specified with the variable, it invokes an error.
  • If the passed argument is the wrong type, like how passing a string to the function is a wrong type because we cannot pass a string to the function.
  • If the curly braces are missing or extra braces are added by mistake which generates the error.
  • It also occurs when the parenthesis in the if statement does not have any expression or result.

As we discussed in the introduction, this is an error and not a piece of code that must have any specified syntax. The following is the error sample of what it looks like.

In the previous error, “element” denotes the keyword in which any expression is missing or added. An expression can be a character, arithmetic value, braces, or a relational expression.

Now, we perform an example in which we perform an addition of two variables in a user-defined function and then display the sum of both values. Let us include our “iostream” and “string” header files. Iostream is used to enable the compiler to use the inbuilt I/O operations that are provided by it where the string enables us to work with the collection of characters. Next, we declare a user-defined function named “myfunct()” to which we pass two arguments for the variables that are calculated. Inside this function, we declare a variable named addition which is responsible for holding the sum of “var1” and “var2 variables.

Now, heading to the main function where we define the integer value “result” to which we assign the myfunct() method by passing two integer values, “20” and “30”. After that, we execute the return value of the function that is stored in the “result” variable using the cout statement that is provided by the iostream library.

int myfunct ( int var1, int var2 ) {

int addition ;
addition = var1 + var2 ;
return addition ;
}

After the execution of the code, we encounter two errors on line 12 which indicates an issue with the “int” element which means that we cannot pass the datatype along with the variable name as an argument to the function. Arguments are always passed without the datatype to the function call. Now, we remove the error by eliminating the datatypes that we pass to it and then re-execute the code.

After re-execution, we successfully displayed the return value of the addition, as we can see in the following screenshot:

Now, we try another example in which we calculate the length of the word, calculate its permutation, and display it. After including the header files, we declare the three functions. The getdata() function which gets a string from the user. Inside this method, we declare a string variable, “word”. Using the “cin” statement, we get the string from the user and return its value. The second function is the “length_count()” which calculates the length of the string using the method length() and returns its value. The third function is “myfunc()” which checks if the string length is greater than “1”. Then, it calculates the permutation and returns it otherwise. It simply returns the length of the string.

At last, we move to the main function where we declare a string variable named “word” to which we assigned the function call of the getdata(). This means that the data that we have taken from the user is assigned to the “Word” variable and creating another variable which is “wordlength” to which we assign the function call of the length_count() where we pass the “word” variable along with its “string” datatype. At last, using the cout statement, we display the result of the permutation of the string that we have taken from the user and execute the code.

int length_count ( string word ) ;
int myfunc ( int wordLength ) ;

int length_count ( string word )
{

int wordLength ;
wordLength = word. length ( ) ;
return wordLength ;
}

int myfunc ( int wordLength )
{

if ( wordLength == 1 )
{
return wordLength ;
}
else
{
return wordLength * myfunc ( wordLength — 1 ) ;
}
}

int main ( )
{
string word = getdata ( ) ;
int wordLength = length_count ( string word ) ;

After the execution, we get this error which displays that we made a mistake at line 43. We pass the datatype to the function along with the variable. As we know, we cannot pass the datatype to the variable. Now, we try to resolve this error by removing the datatype from the function call and execute it again.

After executing the code again, we successfully displayed the message to have the value from the user as we enter the “js” string. After that, the permutation of the code is displayed as shown in the following:

Conclusion

In this article, we studied the type of error which may be encountered while writing the code. Sometimes, the coder may miss something or he/she may add an expression or declared a wrong syntax for the functions or statements by mistake. By using the detailed review and implementing the examples, we briefly described the error and the reason for which this error may be encountered. We also discussed the methodology to resolve these errors. We hope that this article is helpful for you to resolve these kinds of errors.

About the author

Omar Farooq

Hello Readers, I am Omar and I have been writing technical articles from last decade. You can check out my writing pieces.

Источник

Expected primary-expression before ‘int’

Исправить ошибку «expected primary-expression before ‘int'»
У меня есть простая функция в классе func1(int i) и я пытаюсь написать следующую функцию: void *.

Expected primary-expression before
строка с ошибкой выделена /////////////////////// разъясните что не так ( учусь только , хочу.

Лучший ответ

Сообщение было отмечено Ismet как решение

Решение

Эксперт CЭксперт С++

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

cout"Plus=:"int pl(int a[10])endl; // вот тут ошибка((

А что вы вообще хотели сказать вот этим int pl(int a[10]) ? Что это должно было делать — по вашей задумке?

вызываю функцию int pl(int x[]); с параметром a[10]

Добавлено через 3 минуты
Поможете?

Ismet, вы путаете понятия вызов функции и её декларирование. Посмотрите примеры работы с функциями в любой книжке

Добавлено через 2 минуты
да уже понял в чем ошибка и вам спасибо вы даже не поверите у меня на книге все с ошибками вот и трудно оченьгод 2012

Expected primary-expression before ‘[‘ token
Здравствуйте. есть простой код, который написан в среде разработки Dev-C++ 4.9.9.2 #include.

Error: expected primary-expression before ‘p’|
Вот условие Создать класс, содержащий сведения о количестве изделий, собранный сборщиками цеха за.

Ошибка: expected primary-expression before ‘catch’
Компилятор выдает ошибки "error: expected primary-expression before ‘catch’ " "error: expected.

Ошибка: expected primary-expression before ‘.’ token
В этом коде выдает такую ошибку: Widget::Widget(QWidget *parent) : QWidget(parent), .

Источник

Исправить ошибку «expected primary-expression before ‘int'»

Исправить ошибку «expected primary-expression»
Уважаемые форумчане помогите разобраться с простейшей арифметической программой: #include.

Ошибка «expected primary-expression before ‘char'» при объявления переменной
#include <iostream> #include <cstring> #include <cstdio> using namespace std; void.

Ошибка expected primary-expression before «long»
#include<iostream> #include<cstdlib> #include<math.h> using namespace std; int main(void)

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

static_cast тут не при чем. Здесь надо передать объект типа int, а не объявлять его. А откуда его взять, этот объект, только автор кода знает. В качестве абстрактного примера, сойдет вот это:

void * myClass::func2(void * arg) { int i = 42; static_cast myClass* >( arg ) -> func1(i); return NULL; }

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

Эксперт CЭксперт С++

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

( static_cast myClass* >( arg ) ) -> func1(int i);

Эксперт CЭксперт С++

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

Сначала объясните, что вы имели в виду под int i в

( static_cast myClass* >( arg ) ) -> func1(int i);

Никто не может вам подсказать «как правильно написать», пока вы сами вразумительно не объясните, что именно вы пытаетесь сделать.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
class Server { private: int _SocketFileDescriptor,_Port,_ClientAddressLength,_SocketType,_ProtocolFamily; static int a; pthread_t _ReceivingThread; struct sockaddr_in _ServerAddress, _ClientAddress; bool _IsSetuped,_IsStarted; char _Buffer[1024]; static void * receiveInThread(void * arg); public: Server(); void SetParameters(const char * serverAddress,int port,int protocolFamily,int socketType); void Start(); void Stop(); virtual ~Server(); void ReceiveData(); int StartReceiveingThread(); int WaitReceiveingThread(); }

С помощью него, я в отдельном потоке прослушиваю порт на входящие данные. Конструкция такая: есть функция

void * Server::receiveInThread(void * arg){ ( static_cast Server* >( arg ) ) -> ReceiveData(); return NULL; }
int Server::StartReceiveingThread() { return pthread_create( &_ReceivingThread, NULL,Server::receiveInThread, this ); }

Все это помогает мне именно с помощью pthread запустить прослушку в отдельном потоке. Сейчас, я пытаюсь написать функцию для передачи данных, тоже по аналогии с этим, но, функция передачи имеет аргументы, в отличие от функции прослушки. Вот. Подскажите пожалуйста как реализовать такое:
с помощью обычной функции передачи

void * Server::sendInThread(void * arg){ ( static_cast Server* >( arg ) ) -> SendData(int i); return NULL; }

Источник

Читайте также:  What is public static method in java
Оцените статью