views:

2775

answers:

10

I wonder where constant variables are stored. In the same memory area as global variables? Or on the stack?

+11  A: 

How they are stored is an implementation detail (depends on the compiler).

For example, in the GCC compiler, on most machines, read-only variables, constants, and jump tables are placed in the text section.

Robert Harvey
This is probably the one true answer (though it would be more helpful to provide popular implementation methods after pointing this out.)
Lee B
Simply stating "implementation detail", while correct, may not be the "best" answer here. I would guess were dealing with a curious beginner, and as such, the challenge here is figuring out, and replying, "I think you meant to ask *this* and, as such, I think you want to read *that*".
mizipzor
@Lee: If it's "implementation defined", any relying on "popular implementation methods" means your code might break on the next compiler update. Sadly enough, this is not understood by all, so many of those who do understand don't "provide" information on particular implementations, in hopes that the non-understanding types get the hint...
DevSolar
+1  A: 

Usually they are stored in read-only data section (while global variables' section has write permissions). So, trying to modify constant by taking its address may result in access violation aka segfault.

But it depends on your hardware, OS and compiler really.

elder_george
"So, trying to modify constant by taking its address may result in access violation aka segfault." Oh, if only that were true here on OS X. I just tested it, and it scarily works.
Chris Lutz
@Chris: Interesting! :D
Michael Foukarakis
On Windows, e.g. it works only for some compilers. e.g. VC++ and gcc generate such code, but borland one's don't (at least they didn't last time I used them; things may have changed).
elder_george
+1  A: 

This is mostly an educated guess, but I'd say that constants are usually stored in the actual CPU instructions of your compiled program, as immediate data. So in other words, most instructions include space for the address to get data from, but if it's a constant, the space can hold the value itself.

Lee B
+1  A: 

Depends on your compiler, your system capabilities, your configuration while compiling.

gcc usually puts read-only constants on the .text section, unless instructed differently.

Michael Foukarakis
A: 

Global and constant are two completely separated keywords. You can have one or the other, none or both.

Where your variable, then, is stored in memory depends on the configuration. Read up a bit on the heap and the stack, that will give you some knowledge to ask more (and if I may, better and more specific) questions.

mizipzor
+4  A: 

Consider the code:

const int i = 0;
static const int k = 99;

int function(void)
{
    const int j = 37;
    totherfunc(&j);
    totherfunc(&i);
  //totherfunc(&k);
    return(j+3);
}

Generally, i can be stored in the text segment (it's a read-only variable with a fixed value). If it is not in the text segment, it will be stored beside the global variables. Given that it is initialized to zero, it might be in the 'bss' section (where zeroed variables are usually allocated) or in the 'data' section (where initialized variables are usually allocated).

If the compiler is convinced the k is unused (which it could be since it is local to a single file), it might not appear in the object code at all. If the call to totherfunc() that references k was not commented out, then k would have to be allocated an address somewhere - it would likely be in the same segment as i.

The constant (if it is a constant, is it still a variable?) j will most probably appear on the stack of a conventional C implementation. (If you were asking in the comp.std.c news group, someone would mention that the standard doesn't say that automatic variables appear on the stack; fortunately, SO isn't comp.std.c!)

Note that I forced the variables to appear because I passed them by reference - presumably to a function expecting a pointer to a constant integer. If the addresses were never taken, then j and k could be optimized out of the code altogether. To remove i, the compiler would have to know all the source code for the entire program - it is accessible in other translation units (source files), and so cannot as readily be removed. Doubly not if the program indulges in dynamic loading of shared libraries - one of those libraries might rely on that global variable.

(Stylistically - the variables i and j should have longer, more meaningful names; this is only an example!)

Jonathan Leffler
"(if it is a constant, is it still a variable?)" By definition, no.
Chris Lutz
`j` can surely be seen as a variable. The word "variable" is not defined in `C`, but in C++ `j` is a variable. `variable` is just a named object then, be it const or not. In C, literals and enumerators are called `constants` - i don't think that `j` is called a "constant" in C, also because it cannot appear in constant expressions.
Johannes Schaub - litb
A: 

Some constants arfen't even stored.

Consider the following code: int x = foo(); x *= 2;. Chances are that the compiler will turn the multiplication into x = x+x; as that reduces the need to load the number 2 from memory.

MSalters
...or to a constant multiplication, where the 2 would be stored in the actual CPU instruction
Isak Savo
A: 

It may not be stored at all.

Consider some code like this:

#import<math.h>//import PI
double toRadian(int degree){
  return degree*PI*2/360.0;
}

This enables the programmer to gather the idea of what is going on, but the compiler can optimize away some of that, and most compilers do, by evaluating constant expressions at compile time, which means that the value PI may not be in the resulting program at all.

tomjen
A: 

Depending on the data segmentation that a particular processor follows, we have five segments:

1) Code Segment - Stores only code, ROM 2) BSS (or Block Started by Symbols) segment - Stores initialised global and static variables 3) Stack segment - stores all the local varialbles and other informations regarding function return address etc 4) Heap segment - all dynamic allocations happens here 5) Data segment - stores uninitialised global and static variables

Note that the difference b/w BSS and data segment is that the former store initialized global and static varialbes and the later stores UNinitialised ones.

Now, Why am I talking about the data segmentation when I must be just telling where are the constant variables stored... there's a reason to it...

Every segment has a write protected region where all the constants are stored.

For example,

if I have a const int which is local variable, then it is stored in the write protected region of stack segment. and if I have a global that is initialised const var, then it is stored in BSS and if I have an uninitialised const var, then it is stored in data segment...

To summarize, "const" is just a data QUALIFIER, which means that first the compiler has to decide which segment the variable has to be stored and then if the variable is a const, then it qualifies to be stored in the write protected region of that particular segment.

I hope this would clarify most of the misunderstandings.... :-)

Any further comments are welcome... :-)

wrapperm
A: 

Strongly disagree with your points ......

  1. Data segment stores initialized global varibale. and BSS stores unintiliased global varibale. This is the reason why unintialized global varible always has a value of 0

  2. I dont think, stack segment having write protected area.

    pmap [process pid] -> this will show you the permission of each segmants .

    Please check it out yourself

Sunil