user1492991
user1492991

Reputation: 151

Code outside functions

I have written this code outside all functions:

int l, k;
for (l = 1; l <= node; l++)
{
    for (k = 1; k <= node; k++)
    {
        flow[i][j] = capacity[i][j];
        flow[j][i] = 0;
     }
}

It is giving me the following error on compilation:

shalini@shalini-desktop:~$ g++ -o output fords.cpp
fords.cpp:63: error: expected unqualified-id before ‘for’
fords.cpp:63: error: expected constructor, destructor, or type conversion before ‘<=’ token
fords.cpp:63: error: expected constructor, destructor, or type conversion before ‘++’ tok

Upvotes: 7

Views: 11405

Answers (3)

user3104042
user3104042

Reputation: 1

By declaring a global class variable you can execute code before the execution of main(). Put the code in the class constructor.

Upvotes: 0

Eric J.
Eric J.

Reputation: 150148

Functions organize code so that the instruction pointer can reach the code and execute it.

If the compiler would allow you to write code outside of any function it would never run.

Put the code in a function body.

C++ does allow one case where the code itself is written outside the function body, which is a macro declaration, but the macro must be used in a function body to ever run.

Upvotes: 1

N_A
N_A

Reputation: 19897

You can't write code outside of functions. The only things you can have outside of functions are declarations such as global variable declarations (usually a bad idea), function declarations etc. Try putting it in a function like int main(){}

Upvotes: 18

Related Questions