1

Can I initial a static global variable by calling a function in C language? For example:

static int var_01 = fun();

When I use this in VC6 it succeed. But it failed in GCC 4.6.1. This is very strange. I guess this usage is illegal in C89? Or other reason cause this?

4
  • 3
    You'll need to initialise it to a compile-time constant, so in general no. (Perhaps yes if your function is actually a macro.) Commented Aug 1, 2014 at 3:06
  • @sapi The fun() is an ordinory function.It's strange that it can compile ok with VC6. Commented Aug 1, 2014 at 3:12
  • 1
    @Ezio: Are you sure you are compiling it as C, as opposed to C++? It is valid in C++, but not in C. Commented Aug 1, 2014 at 3:16
  • @AndreyT I edit this in C file,so I think it should be in C.But as you said,I guess VC may compile it with C++ features. Commented Aug 4, 2014 at 3:23

2 Answers 2

6

In C99 and as far as I know in C89 as well an initializer for an object with static storage duration has to be either a constant expression or an string literal, from the draft C99 standard section 6.7.8 Initialization:

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

and a function call is not a constant expression from section 6.6 Constant expressions which says (emphasis mine):

Constant expressions shall not contain assignment, increment, decrement, function-call, or comma operators, except when they are contained within a subexpression that is not evaluated.98)

gcc generates the same error using both -std=c99 and -std=c89, note I am also using the following flags -Wall -Wextra -pedantic.

In the modern versions of Visual Studio compiler this does not work in C(see it live) but in C++ this does work. So it may be that you are compiling it as C++ in Visual Studio.

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

Comments

1

Because your post is tagged with c. In c, this is a compile error. You must initialize that to constat literals.

See: http://www.geeksforgeeks.org/g-fact-80/

Comments

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.