Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a value live perpetually when there's no reference to it?

Tags:

c

Suppose the following minimal code:

#include <stdio.h>
char character = 'c';
int main (void)
{
    char character = 'b';
    printf("The current value of head is %c", character);
}

I overwrote character within main,
Then what happened to c? Will it be destroyed automatically or live in the memory perpetually?

This comment clicks with me: "variables in C are nothing but named chunks of memory".

like image 584
AbstProcDo Avatar asked Oct 18 '18 13:10

AbstProcDo


People also ask

Why Value types are stored in stack?

Value types can be created at compile time and Stored in stack memory, because of this, Garbage collector can't access the stack. e.g. Here the value 10 is stored in an area of memory called the stack.

How do you return a variable from a function in Rust?

The return keyword can be used to return a value inside a function's body. When this keyword isn't used, the last expression is implicitly considered to be the return value. If a function returns a value, its return type is specified in the signature using -> after the parentheses () .


Video Answer


2 Answers

"shadowing" the global character variable hides the variable from the main function, but it will still be a part of the program.

If character variable was declared as static, then the compiler might warn that character variable is never used and character will be optimized away.

However, character variable is not declared as static; the compiler will assume that character variable might be accessed externally and keep character variable in the memory.

EDIT:

As noted by @Deduplicator, linker optimizations and settings could omit the variable from the final executable, if permitted. However, this is an edge case that won't happen "automatically".

like image 59
Myst Avatar answered Sep 19 '22 21:09

Myst


You have two separate variables named character: one at file scope set to 'c', whose lifetime is the lifetime of the program, and one in main set to 'b', whose lifetime is that of its scope.

The definition of character in main masks the definition at file scope, so only the latter is accessible.

like image 36
dbush Avatar answered Sep 18 '22 21:09

dbush