3

Why the following code return error when variable is declared global.

int add(int x, int y) {
    return x+y;
}


int ab = add(10, 20);
int main(void) {

    printf("%d", ab);
}

But if I call like this:

int add(int x, int y) {
    return x+y;
}


int main(void) {
    int ab = add(10, 20);  // Variable declare inside main
    printf("%d", ab);
}

then it executes without an error.

1
  • 5
    File scope variables can only be initialised with constant expressions. A function call isn't one. Commented May 21, 2013 at 8:00

4 Answers 4

8

Initializers for global variables must be constant, they can't be an arbitrary expression.

Sign up to request clarification or add additional context in comments.

Comments

5

In C language you cannot execute code in the global scope, outside a function and store the return value of the function in a global variable.

Global variables must be constant at initialisation, and when you're doing :

x = func ( ... )

The return of the function is not constant.

Comments

3

From section 3.5.7 Initialization of the C standard:

All the expressions in an initializer for an object that has static storage duration or in an initializer list for an object that has aggregate or union type shall be constant expressions.

and ab has static storage duration but add() is not a constant expression.

Comments

2

Global variables can be initialized by a constant expression. As their values are set at the compilation time, and not in run-time.

1 Comment

s/constant value/constant expression/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.