Home >Backend Development >C++ >Why Can't I Write C Code Outside of Functions?

Why Can't I Write C Code Outside of Functions?

Barbara Streisand
Barbara StreisandOriginal
2024-12-03 22:22:25430browse

Why Can't I Write C   Code Outside of Functions?

Code outside functions

In C , you cannot 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, and so on.

For example, the following code will not compile:

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;
    }
}

This code will give you the following error:

error: expected unqualified-id before ‘for’
error: expected constructor, destructor, or type conversion before ‘<=’ token
error: expected constructor, destructor, or type conversion before ‘++’ tok

To fix this error, you need to move the code into a function. For example, you could put it in a function called main like this:

int main()
{
    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;
        }
    }

    return 0;
}

The above is the detailed content of Why Can't I Write C Code Outside of Functions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn