Expected initializer before int ошибка

You forgot a ; in line 4 of your code dude! (In the image you posted.)

Actually there is no need of line 4: int lsearch(int [], int, int). Because in the next line you are defining the function itself. You can skip the prototype declaration if you wish.

And from next time please post proper code, not just an image. And by code I mean actual code that is causing error. Here the code in your image is different from the one which you have typed in your post!

In your typed code you are calling lsearch as lsearch(arr[], N, ITEM) [line 34]. A call should be made like this: lsearch(arr, N, ITEM).

Here is you corrected code:

#include <iostream>
using namespace std;

int lsearch(int [], int, int);

int main() {
    int N, ITEM, INDEX, ar[20];
    cout << "How many elements? (max 20): " << endl;
    cin >> N;
    cout << "Enter elements: " << endl;
    for (int i = 0; i < N; i++)
        cin >> ar[i];
    cout << "Your array is as follows: " << endl;
    for (int i = 0; i < N; i++)
        cout << ar[i] << endl;
    cout << "Enter the element to be searched for: " << endl;
    cin >> ITEM;
    INDEX = lsearch(ar, N, ITEM);
    if (INDEX == -1)
        cout << "Element not found!" << endl;
    else
        cout << "Item found at index: " << INDEX << " position: " << INDEX + 1 << endl;
    return 0;
}

int lsearch(int ar[], int N, int ITEM) {
    for (int i = 0; i < N; i++)
        if (ar[i] == ITEM)
            return i;
    return -1;
}

Sample Run:

How many elements? (max 20): 5
Enter elements: 1 2 3 4 5
Your array is as follows: 
1
2
3
4
5
Enter the element to be searched for: 4
Item found at index: 3 position: 4

This code is practically the same (I guessed this code from your image):

#include <iostream>
using namespace std;

int lsearch(int[], int, int); // Your line 4 which isn't necessary and where you missed a semi-colon!
int lsearch(int ar[], int N, int ITEM) {
    for (int i = 0; i < N; i++)
        if (ar[i] == ITEM)
            return i;
    return -1;
}

int main() {
    // same as in above code
}

You should also check out this thread on why «using namespace std» is considered a bad practice.

Студворк — интернет-сервис помощи студентам

Здравствуйте

Я новичок в C++ и недавно столкнулся с такой ошибкой
при передачи массива в функцию

error: expected initializer before ‘int’

ошибка ругается на int main() и не знаю как ее исправит

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <conio.h>
 
using namespace std;
 
int pozishn[10]{0,1,1,1,0,0,0,0,0,0};
 
int check(int poz[])
 
int main()
{
    check(pozishn[])
}
 
int check(int poz[]){
    if(pozishn[1]==1 && pozishn[2]==1 && pozishn[3]==1){
            std::cout << "X" <<std::endl;}
    return 0;
}

expected initializer before ‘int’

prog3.cpp:10:1: error: expected initializer before ‘int’
int main ()
^
this is what i get when i run this program please any help regarding this it will be much appreciated and please tell me if i made this program workable like with boolean expression if the function and prototype are well declared and performing together

/*This program ask user to input Hour, Minute and seconds and if the user
put in the valid format it runs othervise it says error. */

#include <cstdio>

bool readTime(int &hours, int &minutes, int &seconds)

int main ()
{
int h,m,s;
if(readTime(h,m,s)){
printf(«%2d:%2d:%2d» h, m, s);
return 0;
}
}

bool readTime(int &hours, int &minutes, int &seconds);
{
int hh,mm,ss;

printf(«please enter time in format 09:30:50n»);
int count = scanf(«%2d:%2d:%2d», &hh, &mm, &ss);
}
// did they get the right format?
if (count !=3){
printf(«Invalid formatn»);
return false;
}
// is the number of hours correct?
if ((hh <0)||(hh >23)){
printf(«Invalid hour %d n», hh);
return false;
}
//is number of minutes wrong?
if ((mm <0)||(mm >0)){
printf(«Invalid Minutes %d n», mm);
return false;
}
//is number of seconds wrong?
if ((ss <0)||(ss >0)){
printf(«Invalid seconds %d n», mm);
return false;
}

}

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <cstdio>

bool readTime(int &hours, int &minutes, int &seconds) ; // semicolon

int main ()
{
    // ...
}

bool readTime(int &hours, int &minutes, int &seconds) //no semicolon
{
    // ...
}

@JLBorges

now this is what i get after doing your instructions

prog3.cpp: In function ‘int main()’:
prog3.cpp:14:28: error: expected ‘)’ before ‘h’
printf(«%2d:%2d:%2d» h, m, s);
^
prog3.cpp:14:35: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=]
printf(«%2d:%2d:%2d» h, m, s);
^
prog3.cpp: In function ‘bool readTime(int&, int&, int&)’:
prog3.cpp:24:8: warning: unused variable ‘count’ [-Wunused-variable]
int count = scanf(«%2d:%2d:%2d», &hh, &mm, &ss);
^
prog3.cpp:25:4: warning: no return statement in function returning non-void [-Wreturn-type]
}
^
prog3.cpp: At global scope:
prog3.cpp:27:4: error: expected unqualified-id before ‘if’
if (count !=3){
^
prog3.cpp:32:4: error: expected unqualified-id before ‘if’
if ((hh <0)||(hh >23)){
^
prog3.cpp:37:4: error: expected unqualified-id before ‘if’
if ((mm <0)||(mm >0)){
^
prog3.cpp:42:4: error: expected unqualified-id before ‘if’
if ((ss <0)||(ss >0)){
^
prog3.cpp:47:1: error: expected declaration before ‘}’ token
}
^

You have extra braces.

You will find it extremely helpful to
1. Indent your code consistently. Use an editor which does this for you.
2. Type the closing brace at the same type you type the opening brace. Use an editor which does this for you.

Here is a «fixed» version. (there’s still some issues, but it will compile with warnings.)

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
34
35
36
37
38
39
40
41
#include <cstdio>

bool readTime(int &hours, int &minutes, int &seconds);

int main ()
{
  int h,m,s;
  if(readTime(h,m,s)){
    printf("%2d:%2d:%2d" h, m, s);
    return 0;
  }
}

bool readTime(int &hours, int &minutes, int &seconds)
{
  int hh,mm,ss;

  printf("please enter time in format 09:30:50n");
  int count = scanf("%2d:%2d:%2d", &hh, &mm, &ss);

  // did they get the right format?
  if (count !=3){
    printf("Invalid formatn");
    return false;
  }
  // is the number of hours correct?
  if ((hh <0)||(hh >23)){
    printf("Invalid hour %d n", hh);
    return false;
  }
  //is number of minutes wrong?
  if ((mm <0)||(mm >0)){
    printf("Invalid Minutes %d n", mm);
    return false;
  }
  //is number of seconds wrong?
  if ((ss <0)||(ss >0)){ 
    printf("Invalid seconds %d n", mm);
    return false;
  }
}

@mobzzi

i run your program but then i see this issue it will be helpful if i get perfectly running program so that i know for my upcoming exam how to make this type of program run. I am currently preparing for my exam. hope to see some help from you guys out there

In function ‘int main()’:
9:26: error: expected ‘)’ before ‘h’
9:33: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=]
In function ‘bool readTime(int&, int&, int&)’:
41:1: warning: control reaches end of non-void function [-Wreturn-type]

This line :
printf("%2d:%2d:%2d" h, m, s);

Should be :
printf("%2d:%2d:%2d", h, m, s); // An extra comma (,)

Last edited on

@sakurasouBusters

thank you for the help but why am i facing problem like this?

progs3.cpp:41:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^

Notice that the compiler provides you with the location of any errors that it encounters.

1
2
In function 'int main()':
9:26: error: expected ')' before 'h'

Line 9, column 26 — usually there’s a filename, too. There’s a missing comma (I missed it, apologies.)

If the problem is a syntax error, the compiler will report the error no earlier than it appears. Look at the location of the first error and then look backwards towards the beginning of the file until you find it.

@mbozzi

thank you for the help its so much appreciated and helpful for my upcoming exam and future programming errors. but can you help me with my issue on line 41?

Topic archived. No new replies allowed.

Error: expected initializer before ‘int’

I can’t figure out whats wrong with my code. When I compile it, the only error I get is «expected initializer before ‘int’ in line 9. I’m still pretty new and uneducated in this, so I’m not too sure what the heck is going on. Any help is appreciated.

    #include <stdio.h>
#include <math.h>
#include <stdlib.h>

    int m, d, year, choice, i, passed, orig, yy; 
    char more = 'y';
    int  days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    int leap(int x)
int main()
{ 
{
  while (more == 'y' || more == 'Y') {
  	printf ("ntThis program will find days passed or date in the year");
  	printf ("nttt1)  Input date (mm/dd/yyyy) to find dates passed");
  	printf ("nttt2)  Input passed days to find date in the year");
  	printf ("nnttYour choice (1/2): ");
  	scanf  ("%d",&choice);	}
  }
  		char letter (int c)
  		{
  		if (c == 1);{
  	
    int daysInMonth = 0;
    int daysPassed = 0;
    int leapyear = 0;     
    printf("nnnttPlease input date (mm-dd-yyyy): ");
    scanf ("%d/%d/%d", &m, &d, &year);
    if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
            leapyear=1;  
      switch(m-1)  {
        case 12:
          daysInMonth=31;
          daysPassed += daysInMonth;             
        case 11:
          daysInMonth=30;
          daysPassed += daysInMonth;
        case 10:
          daysInMonth=31;
          daysPassed += daysInMonth;
        case 9:
          daysInMonth=30;
          daysPassed += daysInMonth;
        case 8:
          daysInMonth=31;
          daysPassed += daysInMonth;
        case 7:
          daysInMonth=31;
          daysPassed += daysInMonth;
        case 6:
          daysInMonth=30;
          daysPassed += daysInMonth;
        case 5:
          daysInMonth=31;
          daysPassed += daysInMonth;
        case 4:
          daysInMonth=30;
          daysPassed += daysInMonth;
        case 3:
          daysInMonth=31;
          daysPassed += daysInMonth;
        case 2:
          if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0){
            leapyear=1;
            daysInMonth=29;
            daysPassed += daysInMonth;
          }  
          else{
            daysInMonth=28;
            daysPassed += daysInMonth;
          }    
        case 1:
          daysInMonth=31;
          daysPassed += daysInMonth;
        case 0:  
          if(m <=7 && m % 2 != 0 && d <= 31 || m >= 8 && m % 2 == 0 && d <= 31)   
            daysPassed += d;
          else 
            if(m == 2 && leapyear == 1 && d <= 29 || m == 2 && leapyear == 0 && d <= 28)
              daysPassed += d;
            else
             if(m <=6 && m % 2 == 0 && d <= 30 && m != 2|| m >= 9 && m % 2 != 0 && d <= 30)
               daysPassed += d;
             else{
               printf("ntttYour input mm/dd/yyyy is wrong!");     
               break;        
             }           
        printf("nntttThere are %d days past in the year", daysPassed);          
        break;   
        default: printf("ntttYour input mm/dd/yyyy is wrong!");
    	}
    }
	 	if (c == 2)
{
	{
    if (x % 4 == 0 && x % 100 != 0 || x % 400 == 0)
        return 1;
    else
        return 0;
}


    
    do   {
        printf ("nttInput days: ");
        scanf  ("%d", &passed);
        printf ("ntt      Year: ");
        scanf  ("%d", &yy);
        
        if (leap(yy))
            days[1] = 29;
        else
            days[1] = 28;
        
        orig = passed;
        
        for (i = 0; passed > 0; i++)
            passed = passed - days [i];
        passed = passed + days [i - 1]; 
        
        printf ("nttThe date is %d-%d-%d",
                                            i, passed, yy, orig);
		}
        printf ("nnttDo more (Y/N)? ");
        scanf  ("%s", &more);		}
       }while (more == 'y'  ||  more == 'Y');
   
  return 0;        
}

Here’s the whole code:

/
A basic example of Win32 programmiwng in C.

This source code is in the PUBLIC DOMAIN and has NO WARRANTY.

Colin Peters colin@bird.fu.is.saga-u.ac.jp
*/

include <windows.h>

include <string.h>

include <iostream>

/
This is the window function for the main window. Whenever a message is
dispatched using DispatchMessage (or sent with SendMessage) this function
gets called with the contents of the message.
/
LRESULT CALLBACK
MainWndProc (HWND hwnd, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
/
The window handle for the «Click Me» button. /
static HWND hwndButton = 0;
static int cx, cy;/
Height and width of our button. */

HDC hdc;/ A device context used for drawing /
PAINTSTRUCT ps;/ Also used during window drawing /
RECT rc;/ A rectangle used during drawing /
/
Perform processing based on what kind of message we got.
/
switch (nMsg)
{
case WM_CREATE:
{
/
The window is being created. Create our button
window now. /
TEXTMETRIC tm;

/ First we use the system fixed font size to choose
a nice button size. */
hdc = GetDC (hwnd);
SelectObject (hdc, GetStockObject (SYSTEM_FIXED_FONT));
GetTextMetrics (hdc, &tm);
cx = tm.tmAveCharWidth * 30;
cy = (tm.tmHeight + tm.tmExternalLeading) * 2;
ReleaseDC (hwnd, hdc);

/ Now create the button /
hwndButton = CreateWindow (
«button»,/ Builtin button class /
«Click Here»,
WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON,
0, 0, cx, cy,
hwnd,/ Parent is this window. /
(HMENU) 1,/ Control ID: 1 /
((LPCREATESTRUCT) lParam)->hInstance,
NULL
);

return 0;
break;
}

case WM_DESTROY:
/ The window is being destroyed, close the application
(the child button gets destroyed automatically). */
PostQuitMessage (0);
return 0;
break;

case WM_PAINT:
/ The window needs to be painted (redrawn). /
hdc = BeginPaint (hwnd, &ps);
GetClientRect (hwnd, &rc);

/ Draw «Hello, World» in the middle of the upper
half of the window. */
rc.bottom = rc.bottom / 2;
DrawText (hdc, «Hello, World!», -1, &rc,
DT_SINGLELINE | DT_CENTER | DT_VCENTER);

EndPaint (hwnd, &ps);
return 0;
break;

case WM_SIZE:
/ The window size is changing. If the button exists
then place it in the center of the bottom half of
the window. /
if (hwndButton &&
(wParam == SIZEFULLSCREEN ||
wParam == SIZENORMAL)
)
{
rc.left = (LOWORD(lParam) — cx) / 2;
rc.top = HIWORD(lParam) * 3 / 4 — cy / 2;
MoveWindow (
hwndButton,
rc.left, rc.top, cx, cy, TRUE);
}
break;

case WM_COMMAND:
/ Check the control ID, notification code and
control handle to see if this is a button click
message from our child button. /
if (LOWORD(wParam) == 1 &&
HIWORD(wParam) == BN_CLICKED &&
(HWND) lParam == hwndButton)
{
/ Our button was clicked. Close the window. /
DestroyWindow (hwnd);
}
return 0;
break;
}

/ If we don’t handle a message completely we hand it to the system
provided default window function. */
return DefWindowProc (hwnd, nMsg, wParam, lParam);
}

int STDCALL

WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nShow)
{
HWND hwndMain;/ Handle for the main window. /
MSG msg;/ A Win32 message structure. /
WNDCLASSEX wndclass;/ A window class structure. /
charszMainWndClass = «WinTestWin»;
/
The name of the main window class */

/
First we create a window class for our main window.
*/

/ Initialize the entire structure to zero. /
memset (&wndclass, 0, sizeof(WNDCLASSEX));

/ This class is called WinTestWin /
wndclass.lpszClassName = szMainWndClass;

/ cbSize gives the size of the structure for extensibility. /
wndclass.cbSize = sizeof(WNDCLASSEX);

/ All windows of this class redraw when resized. /
wndclass.style = CS_HREDRAW | CS_VREDRAW;

/ All windows of this class use the MainWndProc window function. /
wndclass.lpfnWndProc = MainWndProc;

/ This class is used with the current program instance. /
wndclass.hInstance = hInst;

/ Use standard application icon and arrow cursor provided by the OS /
wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wndclass.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor (NULL, IDC_ARROW);

/ Color the background white /
wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);

/
Now register the window class for use.
*/
RegisterClassEx (&wndclass);

/
Create our main window using that window class.
/
hwndMain = CreateWindow (
szMainWndClass,/
Class name /
«Hello»,/
Caption /
WS_OVERLAPPEDWINDOW,/
Style /
CW_USEDEFAULT,/
Initial x (use default) /
CW_USEDEFAULT,/
Initial y (use default) /
CW_USEDEFAULT,/
Initial x size (use default) /
CW_USEDEFAULT,/
Initial y size (use default) /
NULL,/
No parent window /
NULL,/
No menu /
hInst,/
This program instance /
NULL/
Creation parameters */
);

/
Display the window which we just created (using the nShow
passed by the OS, which allows for start minimized and that
sort of thing).
*/
ShowWindow (hwndMain, nShow);
UpdateWindow (hwndMain);

/
The main message loop. All messages being sent to the windows
of the application (or at least the primary thread) are retrieved
by the GetMessage call, then translated (mainly for keyboard
messages) and dispatched to the appropriate window procedure.
This is the simplest kind of message loop. More complex loops
are required for idle processing or handling modeless dialog
boxes. When one of the windows calls PostQuitMessage GetMessage
will return zero and the wParam of the message will be filled
with the argument to PostQuitMessage. The loop will end and
the application will close.
/
while (GetMessage (&msg, NULL, 0, 0))
{
TranslateMessage (&msg);
DispatchMessage (&msg);
}
return msg.wParam;
}

  • Expected constructor destructor or type conversion before token ошибка
  • Expected before token ошибка ардуино
  • Expected array ошибка vba excel
  • Expected an indented block python ошибка что значит
  • Exloader ошибка не удалось загрузить файлы модификации