Where and how are constants stored?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

int main()
{
	//const int *p1 = (int*) &(5);  //error C2101: '&' on constant
	//cout << *p1;

	const int five = 5;
	const int *p2 = &(five);
	cout << *p2 << endl;

	char *chPtr = (char*) &("abcde");
	for (int i=0; i<4; i++) cout << *(chPtr+i);
	cout << endl;

I was wondering how constants, either integer or string literal, get stored. My understanding of string literals is that they are created in global static memory upon start of program and persist until program exit. In the case of "abcde" even though I did not give it a variable name I can take it's address (chPtr) and I assume I could probably dereference chPtr any time before program termination and the character values would still be there, even if I dereferenced it outside the scope where it was declared. Is the const int variable "five" also placed in global static and that address p2 can also be referenced anytime?

Why can I take the address of "five" but I cannot ask for: &(5) ???? Are the constants "5" and "five" stored differently?
Yes.

'five' is an allocated memory space (hence, it has an address in a data segment).

'5' is just plugged in to the generated machine code (hence, it has no address). (Well, technically it does, but tracking that address in the code segment is not worth the effort to do something weird -- particularly as that value may be bit-packed with other values [as it would be on a MIPS processor].)

To learn more, you'll have to take a class or read a book on assembly language programming and machine architecture.


However, you should avoid doing these kinds of things. Don't try to escape the language's constructs. They are there to provide safety and convenience. When you try to dodge around them then you get in trouble.

Hope this helps.
I hear what you're saying about safety, I'm definitely not ready to escape constructs, even when I try to stay well within bounds I still shoot myself in the foot all the time! It's just that I was curious, I could sort of understand the different treatment of "five" vs. "5" since one is a named variable. I guess it was really the "5" vs. "abcde" that kind of puzzles me, since in that case neither constant is assigned a variable name but yet I can take the address of one and not the other. But like you said, I'll probably need to get into assemly for that level of detail, and right now I've barely scratched the surface of C++. When I do get to that point, do you know of any good Assembly books?

Well thanks for the feedback Duoas, much appreciated.
Last edited on
The difference is really that '5' is a single integer value, where "abcde" is an array of six values -- and the processor doesn't handle structured types directly. It must be stored somewhere, and its address (an integer value) is passed around.
Topic archived. No new replies allowed.