Skip to main content

Global vs local; & and * operators

Short answer

Global variables, functions, and data types declared outside all functions are accessible throughout the program; local ones are confined to their block. The & operator gives a variable’s memory address; the * operator dereferences a pointer to access the pointed value.

What are the differences between global and local function, variables and data types, & (Ampersand) operator and * operators used in c-programming language? Explain with example.

Global versus local

PointGlobalLocal
VariableDeclared outside all functions; visible to all functions below itDeclared inside a function or block; visible only there
Lifetime of variableWhole programOnly while the function/block runs
Default value0Garbage (undefined)
FunctionOrdinary function, can be called from any file/function (external linkage)static function, usable only inside its own file
Data typeStructure or typedef declared outside functions can be used by all functionsDeclared inside a function, usable only there
MemoryData segmentStack

& and * operators

& (address-of)* (indirection)
Gives the memory address of a variableGives the value stored at an address (and is used to declare a pointer)
p = &x;y = *p;
Used with scanf("%d", &x)Used to read or change a value through a pointer
#include <stdio.h>
int g = 100;                    /* global variable */
void show(void)
{
    int g2 = 5;                 /* local variable */
    printf("g = %d, g2 = %d\n", g, g2);
}
int main(void)
{
    int x = 20, *p;
    p = &x;                     /* & gives address of x */
    *p = *p + 5;                /* * gives value at the address */
    g = g + 1;
    show();
    printf("x = %d, *p = %d\n", x, *p);
    return 0;
}

Output:

g = 101, g2 = 5
x = 25, *p = 25

g is global, so show() can use it; g2 is local to show(). p = &x stores the address of x, and *p = *p + 5 changes x through the pointer.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 3 questions →