user3353209
user3353209

Reputation: 23

Declare a global scope variable const in c++

In C or C++, is it possible to declare a const with global scope, but the definition is set inside a function?

Upvotes: 0

Views: 139

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

What about doing something like (live sample)

const int& MyConstValue(int x) {
    static const int myConstValue = x;
    return myConstValue;
}

int main() {
    std::cout << MyConstValue(5) << std::endl; // This is the 1st call and "wins"
    std::cout << MyConstValue(8) << std::endl;

    return 0;
}

Output is

5
5

At least for this is even guaranteed to be thread safe.

Upvotes: 4

Deduplicator
Deduplicator

Reputation: 45674

No, that is impossible. The declaration must be in the same scope as the definition. Otherwise, it's not the same name.

Upvotes: 1

Related Questions