1

Does static make sense below (I'm coming from a Java background)? It compiles, but what's the convention/standard?

#ifndef FUNC_H
#define FUNC_H

int func(const int& x, const int& y);

//cache frequently used values
const static int a = func(2, 0);
const static int b = func(3, 0);

#endif // FUNC_H
Agrim Pathak
  • 3,047
  • 4
  • 27
  • 43
  • 1
    Assuming that this is a header file, a unique copy of each `static` variable will be instantiated in each source file that includes this header file. Assuming that `func` returns the same output for the same input, all those instances will be identical across different source files to begin with. And since these variables are read-only, there is no point in instantiating different copies of them which are initialized to the same value. Bottom line - the `static` is redundant. – barak manos Oct 28 '14 at 20:08
  • On the other hand, if you include this header file in more than one source file, then you will get linkage errors without the `static`. I would declare them `extern` instead of the `static`, and initialize them (by calling `func`) in one of the source files instead of in the header file. – barak manos Oct 28 '14 at 20:10
  • 2
    BTW: It really is uncommon to see builtin types needlessly passed as `const&` instead of by-value. – Deduplicator Oct 28 '14 at 20:16
  • @Deduplicator So there's no performance gains passing built-in types by reference instead of by value? – Agrim Pathak Oct 28 '14 at 20:28
  • 2
    Very few builtin types are bigger than a pointer on desktop-systems (a few more on embedded platforms). For those, sometimes, there might possibly an advantage to not copying them. Though that's rare, due to costs for indirection, aliasing and so on. – Deduplicator Oct 28 '14 at 20:32

2 Answers2

3

In such a context, the static keywords means file scope, as in C.
Probably not what you want in a public header.

Want you want is probably extern, in your header file:

extern const int a;
extern const int a;

It will declare two global variables.
You'll then need a definition, in some .cpp file:

const int a = 42;
const int b = 43;

About file scope, it means that the visibility of such a declaration will be limited to the file in which it is declared. The linker won't generate a public symbol for this.
So if you use this in a header file, a different declaration will be issued in each file where the header is included.

Macmade
  • 52,708
  • 13
  • 106
  • 123
2

Assuming it's a header, this "const static" constant doesn't look good... What it does is create "local" (file scope - so visible only in the file) constant in EACH source file that includes your header. So if you include this header in 10 source files, you'll get 10 copies of this constant, 10 calls to func() etc. All of them will probably have the same value (it depends on the func()).

Technically this is correct, but it just doesn't look good.

Freddie Chopin
  • 8,440
  • 2
  • 28
  • 58