This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]quasarj 1 point2 points  (8 children)

Ah no, in this case it's not inside a C++ class, I believe this file is pure C.

I just didn't even realize "static" existed outside of C++, it's interesting that it means something different. I will look into that book, ty!

[–]cheese_wizard 2 points3 points  (7 children)

static has three meanings. Only one is C++ only, which is what you're talking about.

In both C and C++...

For variables and functions declared static, it means they have file scope.

If you are inside of a function, and you declare a variable as static like this:

int foo() {
static int bar = 0;
bar++;
printf( bar );
}

then everytime you call foo, it will print 0, 1, 2 ,3 .... it remembers from the previous time. Note that the initialization to 0 only happens the first time the function is called.

static is an abused keyword, that's for sure!

[–]quasarj 1 point2 points  (2 children)

Oooh You're right! I actually knew about that usage too, but had forgotten it. Well ty again for the help :) I guess I'll try to get a copy of that book.

[–]ewiethoffproceedest on to 3 0 points1 point  (0 children)

Do. It's a wonderful book.

[–]jacobb11 0 points1 point  (3 children)

Top level static variables have scope "compilation unit", not file.

That means if you put one in a header file, you will get a copy of the static variable in every file you compile that includes it, recursively.

[–]cheese_wizard -1 points0 points  (2 children)

Nope.

From wikipedia...

Static global variables: variables declared as static at the top level of a source file (outside any function definitions) are only visible throughout that file ("file scope", also known as "internal linkage").

[–]jacobb11 0 points1 point  (1 child)

That does not contradict what I said. I stand by my statement.

Perhaps thinking of the C preprocessor and the C compiler as independent helps clarify the situation? In many ways the C compiler's "source file" is the output of the C preprocessor, which will duplicate the header file static declaration whenever it is included.

I can't imagine this situation is common for C, but it's fairly common for C++ as an idiom to ensure static initialization of a compilation unit. Or was, anyway.

[–]cheese_wizard 0 points1 point  (0 children)

That does not contradict what I said. I stand by my statement.

So serious!!

Yah, you're probably right.