a doubt on const variables

lets take
const int a=10;
as we know during compilation compiler replaces all occurrences of a with corresponding value.

so there is no need for memory as variable is dead after compilation.

but when i print sizeof(a) i am getting 4bytes.

why?
Compiler would try to substute all entries of constant with its value.

It still a variable, you can take its address, pass it as pointer, or have other code "outside" access it. So it is possible to other code which do not know its value in compile time still can use it.

If constant has internal linkage and all access happens in compile time it can be completely optimized out.
as we know ....

Do we?

Besides, you claim that the compiler does place 10 to various places, so your code should contain sizeof(10). That is a valid question, whether you have memory for it or not. How many bytes would I need if I had to store ...
> when i print sizeof(a) i am getting 4 bytes.

sizeof(a) tells us how many bytes would be used by the object representation of an object of type int.
It tells us nothing about whether the variable a has been optimised away or not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int foo()
{
    int a = 34 ; // optimised away
    long long b = a + 45 ; // optimised away
    
    int* pa = &a ; // this pointer too is optimised away
    long long* pb = &b ; // also this'
    
    return *pa < *pb ? sizeof(a) : sizeof(b) ; // return 4 ;
    
    /*
    code generated: 
    
    movl    $4, %eax
    ret
    
    equivalent to: 
    return 4 ;
    */
}

int bar()
{
    return 4 ;   
    /*
    code generated: 
    
    movl    $4, %eax
    ret
    
    */
}

http://coliru.stacked-crooked.com/a/1fefa3e1222cc850
Topic archived. No new replies allowed.