top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Difference between local const variable and global const variable in C ?

0 votes
2,042 views
Difference between local const variable and global const variable in C ?
posted Sep 4, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes

Local constant variable has local scope so that variable can't be accessed.
Global constant variable has global scope so it can be accessed from outside the file.

answer Sep 4, 2014 by Neelam
0 votes

Constant: A variable defined as const tells that the value of the variable can not be changeed.

Local const Variable
Local variable are the variables whose value we can change at different places in the same function or in different function by passing it as argument. But if we attach the word const to it then we can not change the value once declaed.

void myfunc
{
  const int a = 30;  
  int const *p = &a;
  a = 30; //giving compilation error error as it is a const variable.
  *p = 30 // no compilation error
}

Global const variable
A global constant variable is first thing is global so scope is not just local hence can be accessed anywhere in the program but the major thing here is that global const variable is stored in read only memory so whenever you try to change the value using a pointer u get the segmentation fault as memory is readonly. Check the following example -

const int a = 20; //Global const variable
int main()
{
  int const *p = &a; // As p is a pointer to global const variable
  *p = 30;//No compilation error but it will give segmentation fault 
}
answer Sep 5, 2014 by Salil Agrawal
Yes the data is stored in the code section (read only memory) & the pointer holds the address of  code memory. And when trying to write/modify the contents of a read only memory, the operating system generates signal 11 (SIGSEGV) as we are trying to access unauthorized memory.
Similar Questions
0 votes

Trivial question, please help.

I need to convert a string literal like "111.25" to floating point number.
atof() fails me as it returns 1111 and discards .25?

+5 votes

Even I have similar problem:

int (*pfun)(void);
int *pInt = 0;
void fun1()
{
    int i = 5; /* Local to fun1*/

    printf("Outer function");
    pInt = &i; /* As I know address of local variable is valid till function execution */

    int fun2()
    {
      printf("innerfunction");
      printf("%d", *pInt);
    }
    /* fun2 address assign to pfun so that It can be called even after completion of fun1 */
    pfun = fun2;
}

int main()
{
    fun1();
    pfun();
    return 0;
}

Can someone please explain ? I am getting *pInt value 5.

...