0

I have following codes below. However, it is hard for me to determine lifetime and scope of x and *px. I do know the concepts of those terms, though. Should x and *px considered as local variable because it is not declared outside main function or global because it is declared at the start and goes to the end anyway? Confused about static and automatic as well for x and px as well.....

#include <stdio.h> 
int main(void)
{
    double x=3.14, *px = &x;
    printf("ADDR:%p\n", &x);
    printf("ADDR:%p\n", &px);

    return 0;
}
Nathan Lee
  • 75
  • 1
  • 3
  • 10

1 Answers1

0

The lifetime of x and px

Since x and px are local variables of the main-function and the program runs as long as the main-function runs (that's the nature of the main-function), these variables exist throughout the entire runtime of the program. This doesn't make them global, though.

The scope of x an px

x and px are local variables of main(), which means you can only access them directly from inside the main-function.

You can still access them indirectly from any other function if this function happens to have a pointer to one of those variables, but this has nothing to do with the scope of the variables themselves.


To clarify your confusion about static and automatic variables, I would like to refer to this answer which explains this better than I could: Difference between static, auto, global and local variable in the context of c and c++

Fränki
  • 69
  • 3