Post

Variables, Format Specifiers Of C

Variables, Format Specifiers Of C

C Variables – Complete Guide

1. What is a Variable?

A variable in C is a named memory location used to store data. A variable has:

  • Data Type – defines what kind of data it can store.
  • Name – the identifier.
  • Value – the stored data.

2. Declaring and Initializing Variables

Declaration – Reserves memory:

1
int age;   // no value yet

Initialization – Assigns a value:

1
age = 25;

Declaration + Initialization:

1
2
3
4
int age = 25;        // integer
float gpa = 3.75;    // floating-point
char grade = 'A';    // single character
char name[] = "Bro"; // string (array of characters)

3. C Data Types (Basic)

Data TypeExampleTypical Size*
int424 bytes
float3.144 bytes
double3.141598 bytes
char‘A’1 byte
_Bool0 / 11 byte

*Size may vary depending on system and compiler.


4. Variable Scope

Scope defines where a variable can be accessed.

  1. Local Variables – Declared inside functions; exist only within that function.
1
2
3
void func() {
    int x = 5; // local
}
  1. Global Variables – Declared outside all functions; accessible from anywhere.
1
int g = 10; // global
  1. Block Scope – Declared inside {}; accessible only inside that block.
1
2
3
if (1) {
    int y = 20; // block scope
}

5. Storage Classes

Storage classes define lifetime and visibility.

KeywordMeaning
autoDefault for local variables.
staticRetains value between function calls.
externDeclared in another file.
registerSuggests storing in CPU register (faster access).

6. Constants

Constants store fixed values that cannot change.

1
2
const float PI = 3.14;   // constant variable
#define MAX 100          // preprocessor constant

7. Format Specifiers

Used with printf() / scanf() to display or read variables.

Integer

SpecifierMeaning
%d / %iSigned integer
%uUnsigned integer
%oOctal
%x / %XHexadecimal

Floating-Point

SpecifierMeaning
%fDecimal notation
%.nfFixed decimal places
%e / %EScientific notation
%g / %GShortest representation

Character & String

SpecifierMeaning
%cSingle character
%sString

Pointer

SpecifierMeaning
%pMemory address

Special

SpecifierMeaning
%%Prints %

8. Example Program

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>

int globalVar = 100; // global variable

int main() {
    int age = 25;           // integer
    float gpa = 3.75;       // float
    char grade = 'A';       // char
    char name[] = "Bro";    // string
    const float PI = 3.14;  // constant

    printf("Name: %s\n", name);
    printf("Age: %d\n", age);
    printf("GPA: %.2f\n", gpa);
    printf("Grade: %c\n", grade);
    printf("PI: %.2f\n", PI);
    printf("Global Var: %d\n", globalVar);
    printf("Memory address of age: %p\n", (void*)&age);

    return 0;
}
This post is licensed under CC BY 4.0 by the author.