- 2073 Chaitra · 4+4 marks
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
| Point | Global | Local |
|---|---|---|
| Variable | Declared outside all functions; visible to all functions below it | Declared inside a function or block; visible only there |
| Lifetime of variable | Whole program | Only while the function/block runs |
| Default value | 0 | Garbage (undefined) |
| Function | Ordinary function, can be called from any file/function (external linkage) | static function, usable only inside its own file |
| Data type | Structure or typedef declared outside functions can be used by all functions | Declared inside a function, usable only there |
| Memory | Data segment | Stack |
& and * operators
& (address-of) | * (indirection) |
|---|---|
| Gives the memory address of a variable | Gives 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)
Related questions
- Operators; conditional operator · Computer Programming, chapter 3
- Define programming language · Computer Programming, chapter 1 · asked 3×
- Data types and operators in C · Computer Programming, chapter 3
- Define operator, data type, constant, variable · Computer Programming, chapter 3
- I/O functions used with data files · Computer Programming, chapter 10 · asked 2×
- Conditional operator vs if-else; digit sum · Computer Programming, chapter 5
- 8086 assembly language operators · Microprocessor, chapter 3 · asked 3×
- Global unicast, link local, site local, multicast · Internet and Intranet, chapter 2
- Binary operator member function one argument · Object Oriented Programming, chapter 5
- Continuous vs discrete variables, return period formulae · Engineering Hydrology, chapter 6