"static const int" versus "const int"

J

John Goche

Hello,

I would like to ask what the difference is between
"static const int" versus "const int". I mean of course
the former goes in the static data segment of code
whereas the latter is pushed on the stack, but since
a const does not change it might as well be declared
static, but to what advantage.

What I am asking is how to decide whether to use
"static const int" versus "const int".

Thanks,

John Goche
 
V

Victor Bazarov

I would like to ask what the difference is between
"static const int" versus "const int". I mean of course
the former goes in the static data segment of code
whereas the latter is pushed on the stack, but since
a const does not change it might as well be declared
static, but to what advantage.

What I am asking is how to decide whether to use
"static const int" versus "const int".

In what scope? It matters a lot.

V
 
J

John Goche

In what scope?  It matters a lot.

I forgot to mention: inside the block scope
of the body of a function.

Also, as a separate question, what's wrong with

const int foo = 1;

const int bar = foo + 1;

The compiler replies with: error: initializer element is not constant

Of course I could use the preprocessor, but the preprocessor is
not very popular in C++ as it is in C, so what should I do, compose
a function:

const int bar() {
return foo + 1;
}

Seems silly to me.

Thanks,

John Goche
 
J

John Goche

That code is not ill-formed so you are either a) lying or b) have a
broken compiler.

/Leigh

In this case the code was declared outside of any function as a
global variable, and then I get the error, otherwise you are right
it would compile fine inside a function.

Anyways, I still don't have an answer to the two questions I posted.

Thank you for your replies though,

Regards,

John Goche
 
V

Victor Bazarov

I forgot to mention: inside the block scope
of the body of a function.

There is no difference from the behavior POV. Code-generation-wise, an
automatic constant can easily be replaced by the compiler with its value
when used in an expression (so no storage is usually wasted on it at
all), and a static object will cause some storage allocation and
possibly the use of that storage when the variable is used in an
expression. Should you care about that? I don't know.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top