skip to Main Content

I am trying to make this code work on Visual Studio 2022, but it tells me that after the second void printArray(int theArray[], int sizeOfArray) it expected a ;. I am doing this code based on https://youtu.be/VnZbghMhfOY. How can I fix this?

Here is the code I have:

#include <iostream>
using namespace std;

void printArray(int theArray[], int sizeOfArray);

int main()
{
    int bucky[3] = {20, 54, 675};
    int jessica[6] = {54, 24, 7, 8, 9, 99};

    printArray(bucky, 3);

    void printArray(int theArray[], int sizeOfArray)
    {
        for (int x = 0; x < sizeOfArray; x++){
            cout << theArray[x] << endl;
        }
    }
}

I tried to change the code order but that only made it worse, the error saying ; is apparently useless and the whole thing breaks apart if I put it there.

2

Answers


  1. C++ doesn’t have nested functions. You need:

    #include <iostream>
    using namespace std;
    
    void printArray(int theArray[], int sizeOfArray);
    
    int main()
    {
    
        int bucky[3] = {20, 54, 675};
        int jessica[6] = {54, 24, 7, 8, 9, 99};
    
        printArray(bucky, 3);
    
    }
    
    void printArray(int theArray[], int sizeOfArray)
    {
    
        for (int x = 0; x < sizeOfArray; x++)
        {
             cout << theArray[x] << endl;
        }
    }
    
    Login or Signup to reply.
  2. You should take the implementation of the function "printArray" out of the main.

    #include <iostream>
    using namespace std;
    
    void printArray(int theArray[], int sizeOfArray);
    
    int main()
    {
    
        int bucky[3] = {20, 54, 675};
        int jessica[6] = {54, 24, 7, 8, 9, 99};
    
        printArray(bucky, 3);
        return 0;
    }
    void printArray(int theArray[], int sizeOfArray)
    {
        for (int x = 0; x < sizeOfArray; x++){
            cout << theArray[x] << endl;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search