LearnFrenzy
Sign in Take a free test

C Programming · Topic 10 of 23

C Variables

  • 4 exercises
  • 40 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

C Variables · Study material

A variable in C is a named piece of storage with a type. Beyond its name and type, every variable has three properties that interviewers love to ask about: its scope (where the name can be used), its lifetime (when the storage exists) and its linkage (whether other files can see it). Get them wrong and you read garbage, keep stale values, or create clashing globals. This page explains all three, the storage-class keywords, and C23's auto, then gives you 40 practice questions checked on a real compiler.

On this page

  • Declaring, defining and naming variables
  • Default initialisation: when a variable starts at 0 and when it holds garbage
  • Scope, lifetime and linkage – with static, extern, register and thread_local
  • Shadowing, and type inference with C23 auto

Declaring and naming variables

A declaration gives a type and a name: int marks = 85;. Names may contain letters, digits and underscores, must not start with a digit, are case-sensitive, and must not be keywords. Names beginning with an underscore followed by a capital letter (_Count) or with two underscores are reserved for the compiler and library.

NameValid?
total_marks, marks2, _tmpYes
2ndPlaceNo – starts with a digit
float, intNo – keywords
first-nameNo – the hyphen is a minus sign
_Value, __xCompiles, but reserved – avoid

Scope, lifetime and linkage

Where / how declaredScopeLifetimeLinkageStarts as
Inside a functionto the end of the blockautomatic (each entry)nonegarbage
Inside a function, staticto the end of the blockwhole programnone0
Outside all functionsto the end of the filewhole programexternal0
Outside all functions, staticto the end of the filewhole programinternal (this file)0
thread_local (C23; _Thread_local in C11)as declaredone per threadas declared0
#include <stdio.h>

int counter = 0;                 /* file scope, static storage, external linkage */
static int hidden = 5;           /* file scope, internal linkage: this file only */

void visit(void) {
    static int visits = 0;       /* block scope, but it lives for the whole program */
    int local = 0;               /* block scope, automatic: created on every call */
    visits++;
    local++;
    counter++;
    printf("visits=%d local=%d counter=%d\n", visits, local, counter);
}

int main(void) {
    visit();
    visit();
    printf("hidden=%d\n", hidden);
    return 0;
}

Output

visits=1 local=1 counter=1
visits=2 local=1 counter=2
hidden=5

Default initialisation

Variables with static storage – globals and static locals – are zero-initialised before main() starts. Automatic (local) variables are not: reading one before assigning it gives an indeterminate value. Initialise every local at its declaration.

#include <stdio.h>

int global_value;                /* static storage: starts at 0 */

int main(void) {
    static double s;             /* static storage: 0.0 */
    int arr[3] = {0};            /* a local array: zeroed only because of the initializer */
    int *p = &global_value;
    printf("%d %.1f %d %d\n", global_value, s, arr[2], *p == 0);
    return 0;
}

Output

0 0.0 0 1

Block scope and shadowing

A name declared in an inner block hides ("shadows") the same name from an outer block or the file. The outer variable still exists; it just cannot be named until the inner block ends. Compile with -Wshadow to be warned about it.

#include <stdio.h>

int x = 1;

int main(void) {
    printf("%d ", x);            /* the global x */
    int x = 2;                   /* a local x hides the global from here on */
    {
        printf("%d ", x);
        int x = 3;               /* an inner block can hide it again */
        printf("%d ", x);
    }
    printf("%d\n", x);           /* the inner x is gone */
    return 0;
}

Output

1 2 3 2

Declaration vs definition: extern

A definition creates the variable; a declaration only announces its name and type. extern int limit; declares a variable defined elsewhere – usually in another .c file, with the extern line in a shared header. There must be exactly one definition in the whole program; a missing one is a link error.

#include <stdio.h>

extern int limit;                /* declaration: "limit is defined somewhere" */

void show(void) {
    printf("limit = %d\n", limit);
}

int limit = 100;                 /* the one definition (it could be in another .c file) */

int main(void) {
    show();
    limit = 200;
    show();
    return 0;
}

Output

limit = 100
limit = 200

The storage-class specifiers

  • auto – the default for locals (never needed); in C23 it also means "infer the type".
  • register – a hint to keep the variable in a CPU register; you cannot take its address. Compilers ignore the hint today.
  • static – static lifetime for a local; internal linkage for a global or function.
  • extern – refer to a definition that is elsewhere.
  • thread_local – each thread gets its own copy (C23 keyword; _Thread_local since C11).

C23: type inference with auto

In C23, auto with an initializer deduces the variable's type, like C++. Careful: in C a character constant is an int, so auto c = 'A'; is an int.

#include <stdio.h>

int main(void) {
    auto count = 10;             /* C23: the type comes from the initializer: int */
    auto ratio = count / 4.0;    /* double */
    auto letter = 'A';           /* int – a character constant is an int in C */
    printf("%zu %zu %zu\n", sizeof count, sizeof ratio, sizeof letter);
    return 0;
}

Output

4 8 4

Key points to remember

  • Locals start with garbage; globals and statics start at zero.
  • Scope is about the name; lifetime is about the storage.
  • static on a local keeps its value; on a global it hides it from other files.
  • extern declares, it does not define; define each global exactly once.
  • Keep scope small: declare variables where they are first needed.

Frequently asked questions

What is the default value of a local variable in C?

None – it is indeterminate (garbage). Only variables with static storage duration start at zero.

What is the difference between a global and a static global variable?

Both live for the whole program, but a static global has internal linkage: only code in the same .c file can use it.

Are global variables bad?

Mutable globals make code hard to test and reason about, because any function can change them. Prefer parameters, or file-private static variables with accessor functions.

Where can I learn more?

Read Scope and Storage Classes in C and Data Types in C, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C Programming

C programming is the language most computer science courses start with and the foundation of operating systems, embedded devices and compilers. This section helps you learn C properly – data types, operators, control statements, functions, arrays, strings, pointers, structures, memory allocation and files – and then prove it with hundreds of practice questions explained line by line.

Why it matters

  • C teaches how a computer really works: memory, addresses and how data is stored
  • Pointers and memory questions are a favourite in written tests and technical interviews
  • Once you know C, learning C++, Java and Python becomes much easier
  • Embedded systems, operating systems and many companies' coding rounds still use C

Who it is for

  • School students (Class 11–12 computer science) building a strong programming base
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, aptitude-cum-coding tests and technical interviews
  • Anyone preparing for GATE CS or government IT exams

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro tests
  • Technical interviews
  • GATE CS
  • University exams
  • Government IT exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links