C Variables & Data Types: Complete Beginner’s Guide

目次

1. Introduction

The Importance of Variables and Data Types in C

C is a programming language widely used for system programming and embedded system development. When learning C, the “variables” and “data types” are the most fundamental yet important concepts. Programs are built by manipulating data, and to manage that data properly, it is necessary to use variables correctly and choose appropriate data types. For example, when considering a variable to store numbers, the data type differs between handling integers and handling floating-point numbers. It is also important to select the optimal data type considering memory savings and performance improvements.

Purpose of This Article

This article explains C’s “variables” and “data types” in a way that beginners can understand. To enable systematic learning from basic concepts to practical usage, we will cover the following points.
  1. What is a variable? – Explanation of declaration, initialization, naming conventions, etc.
  2. Classification of data types – Primitive data types (int, float, char, etc.) and derived data types (struct, array, pointer, etc.)
  3. Type conversion (casting) – Implicit and explicit type conversions
  4. Variable scope and lifetime – Differences between local and global variables
  5. Practical selection of data types – Choosing the optimal type based on memory usage and computational precision

When Do You Need to Be Mindful of Variables and Data Types?

In C programming, the choice of variables and data types becomes important in the following situations.

Memory Optimization

In embedded systems and low‑level programs, minimizing memory usage is required. By selecting appropriate data types, you can prevent unnecessary memory consumption.
short num1 = 100;  // 2 bytes (16 bits)
int num2 = 100;    // 4 bytes (32 bits)
In the example above, using short saves memory compared to int.

Improving Computational Precision

When dealing with floating‑point numbers, float is less precise than double, but it consumes less memory.
float pi = 3.141592;  // single‑precision floating point (32 bits)
double pi_high = 3.14159265358979;  // double‑precision floating point (64 bits)
For calculations that require high precision, using double is common.

Preventing Bugs Through Type Casting

In C, operations between different data types may be automatically converted. If you do not cast appropriately, you can get unintended results.
int a = 10;
float b = 3.5;
int result = a + b;  // implicit conversion (result is rounded to int)
In this case, result becomes 13, and the fractional part is truncated. To avoid this, explicit casting is required.
float result_correct = (float)a + b;  // correct type conversion

Conclusion

In C programming, choosing the right variables and data types is extremely important. By considering memory efficiency, computational precision, and the impact of type conversions, selecting appropriate data types helps prevent bugs and create efficient programs.

2. What is a Variable?

Basic Concept of Variables

In the C language, variable (Variable) is a “named memory area” that a program uses to temporarily store data. By using variables appropriately when performing calculations or storing data within a program, you can write flexible code.

Characteristics of Variables

  • Memory area for storing data
  • Value can be changed during program execution
  • Allocates memory according to the data type (type) of the data
For example, there are variables that store integer values, variables that store floating-point numbers, and variables that store characters.

Variable Declaration and Initialization

To use variables in C, you first perform a variable declaration. In a variable declaration, you need to specify the data type (type) and variable name.

Basic Variable Declaration Syntax

type variable_name;

Variable Initialization

If you only declare a variable, its value remains undefined. Therefore, by initializing (setting an initial value) you can prevent unintended behavior.
int num = 10;  // Initialize integer variable num with 10
float pi = 3.14;  // Initialize floating-point variable pi with 3.14
char letter = 'A';  // Initialize character variable letter with 'A'

Variable Types in C

In C, you need to define the type of a variable explicitly. The main data types are as follows.
Data TypeDescriptionExample
intInteger typeint a = 10;
floatSingle-precision floating-pointfloat b = 3.14;
doubleDouble-precision floating-pointdouble c = 3.1415926535;
charCharacter typechar d = 'A';
The differences between integer types and floating-point types are explained in detail in the later “Overview of Data Types” section.

Variable Naming Conventions and Best Practices

Rules for Variable Names in C

Variable names can be set freely, but you must follow the rules below. ✅ Allowed characters
  • Alphabet (A-Z, a-z)
  • Digits (0-9) *but cannot be used at the beginning of a variable name*
  • Underscore (_)
🚫 Disallowed
  • Reserved words (e.g., int, float, return, etc.)
  • Special characters (e.g., @, #, $, etc.)
  • Digits at the beginning of a variable name
int _value = 10;  // OK
int number1 = 20;  // OK
int 1st_number = 30;  // NG (Variable names cannot start with a digit)
int return = 100;  // NG (Reserved words cannot be used)

Naming for Readability (Best Practices)

In C, properly naming variables improves code readability. ✅ Good examples
int userAge;  // User's age
🚫 Bad examples
int a;  // Meaningless
👉 Points to Improve Readability
  • Give variable names meaningful names
  • Use camelCase (e.g., userAge) or snake_case (e.g., user_age) for multiple words
  • Avoid abbreviations as much as possible (e.g., use a specific name like numOfStudents)

How to Use Variables (Simple Program)

The following program uses variables to perform a simple calculation and display the result.

Sample Code

#include <stdio.h>

int main() {
    int a = 5;
    int b = 10;
    int sum = a + b;  // calculate using variables

    printf("a = %d, b = %d, sum = %dn", a, b, sum);
    return 0;
}

Output

a = 5, b = 10, sum = 15
In this way, using variables allows you to store calculation results and reuse them.

Summary

  • Variables are memory areas for temporarily storing data
  • In C, you must specify the data type when declaring a variable
  • Variable naming has rules, and naming with readability in mind is recommended
  • Using variables makes data management easier
年収訴求

3. Overview of C Language Data Types

What is a Data Type?

C language determines the kind of data a variable handles and its memory usage by explicitly specifying the data type (Data Type). Choosing the appropriate data type enables memory efficiency and prevention of bugs caused by type conversion.

Characteristics of C Data Types

Clarify the type of data (integers, floating-point, characters, etc.) ✅ Optimize memory usage (memory size varies by type) ✅ Determine behavior of type conversion and operations (calculations between integers, floating-point calculations, etc.) For example, integer types and floating-point types handle different kinds of data as shown below.
int age = 25;        // integer (stores only integer values)
float pi = 3.14;     // floating-point number (can handle decimals)
char letter = 'A';   // character type (stores a single character)

Classification of C Data Types

C data types can be broadly classified into two categories: basic data types and derived data types.
Data Type CategoryOverview
Basic Data TypesFundamental variable types (e.g., int, float, char, etc.)
Derived Data TypesCombinations of basic data types (arrays, structs, pointers, etc.)

Basic Data Types

Basic data types are the most commonly used data types in C programs.

Integer Types

Data types for handling integers, capable of storing both negative and positive values.
Data TypeMemory Size (Standard)Value Range (32-bit environment)
int4 bytes (32-bit)-2,147,483,648 ~ 2,147,483,647
short2 bytes (16-bit)-32,768 ~ 32,767
long4–8 bytesDepends on the environment (wider range than int)
unsigned int4 bytes0 ~ 4,294,967,295
int number = 100;
short smallNumber = 10;
unsigned int positiveOnly = 300;

Floating-Point Types

Data types for handling decimals, with float and double differing in precision.
Data TypeMemory SizePrecision
float4 bytesabout 6–7 digits
double8 bytesabout 15 digits
long double10–16 bytesabout 18+ digits
float pi = 3.14f;  // adding "f" makes it a float type
double precisePi = 3.1415926535;

Character Type

A data type for storing a single character, which is actually treated as a integer (ASCII code).
Data TypeMemory SizeStorable Data
char1 byte‘A’, ‘b’, ‘9’, etc. (single character)
char letter = 'A';
printf("%c", letter);  // outputs A
ASCII code handling allows char to be used in numeric expressions.
char letter = 'A';
printf("%d", letter);  // 65 ('A' ASCII code)

Derived Data Types

Derived data types are used to define advanced data structures by combining basic data types. ArrayStores data of the same type consecutively Struct (struct)Treats different types of data as a single unitUnion (union)Data structure that shares memoryEnum (enum)Defines meaningful constantsPointerVariable that stores a memory address

Criteria for Choosing Data Types

Choosing the appropriate data type impacts program performance and memory management.
Use CaseRecommended Data TypeReason
Loop counterunsigned intNo sign needed, more efficient
High-precision calculationsdoubleHigher precision than float
Want to save memoryshort / charManaged with minimal required size
Handling a single character of a stringcharManages a character in 1 byte
for (unsigned int i = 0; i < 100; i++) {
    printf("%d ", i);
}

Summary

  • C data types include basic data types (integer, floating-point, character) and derived data types (arrays, structs, pointers, etc.).
  • Choosing the appropriate data type can improve program efficiency.
  • Integer types: int; floating-point types are common.
  • Utilizing derived data types makes handling complex data structures easier.

4. Basic Data Types (Primitive Types)

What are basic data types?

C language’s basic data types (primitive types) are the types that represent the most fundamental kinds of data and form the basis of all variables and data structures. By understanding these types and selecting them appropriately, you can achieve program efficiency and optimized memory management. C has mainly the following three kinds of basic data types.
Data TypeDescriptionExample
Integer type (Integer)Type that handles integersint, short, long
Floating-point type (Floating Point)Type that handles floating-point numbersfloat, double
Character type (Character)Type that handles a single characterchar
We will now discuss each data type in detail.

1. Integer type (Integer)

The integer type is a data type for storing integers and is one of the most frequently used types in programs.

Kinds of integer types and memory sizes

Integer types include signed and unsigned variants.
Data TypeMemory Size (standard)Value range (32-bit environment)
int4 bytes (32-bit)-2,147,483,648 ~ 2,147,483,647
short2 bytes (16-bit)-32,768 ~ 32,767
long4–8 bytesDepends on the environment (wider range than int)
unsigned int4 bytes0 ~ 4,294,967,295

Example of integer types

#include <stdio.h>

int main() {
    int num = 100;         // General integer type
    short smallNum = 10;   // Small integer (memory saving)
    long bigNum = 1000000; // Large integer
    unsigned int positiveOnly = 300; // Positive integers only

    printf("num: %d, smallNum: %d, bigNum: %ld, positiveOnly: %un", num, shortNum, bigNum, positiveOnly);
    return 0;
}

2. Floating-point type (Floating Point)

The floating-point type is a data type for handling fractional numbers. Unlike integer types, it can represent fractions accurately.

Kinds of floating-point types

Data TypeMemory SizePrecision (significant digits)
float4 bytesabout 6–7 digits
double8 bytesabout 15 digits
long double10–16 bytesabout 18+ digits

Example of floating-point types

#include <stdio.h>

int main() {
    float pi = 3.14f;         // Adding "f" makes it a float type
    double precisePi = 3.1415926535;  // Higher-precision double type

    printf("pi (float): %.7fn", pi);
    printf("precisePi (double): %.15lfn", precisePi);
    return 0;
}

3. Character type (Character)

The character type (char) is a data type for storing a single character and is actually treated as a integer (ASCII code).

Features of the character type

  • Uses 1 byte (8 bits) of memory
  • char type uses ASCII codes and is internally treated as an integer

Example of character type

#include <stdio.h>

int main() {
    char letter = 'A';  // Store a character
    printf("letter: %cn", letter);
    printf("ASCII code: %dn", letter);  // 'A' is 65

    return 0;
}

Appropriate selection of basic data types

Which basic data type to use is decided based on the program’s purpose and memory constraints.
Use caseRecommended data typeReason
Loop counterunsigned intNo negative numbers needed, more efficient
Floating-point calculationsdoubleHigher precision than float
Memory savingshort / charManaged with the minimum required size
Handling a single character of a stringcharCan be managed in 1 byte
short smallNum = 32767;  // Save memory

Summary

  • Basic data types are the foundation of C programs and handle integers, floating-point numbers, and characters
  • Integer types (int, short, long) handle integers, and unsigned (unsigned) can also be used
  • Floating-point types (float, double) handle fractional numbers and are chosen based on precision needs
  • Character type (char) handles a single character and is stored internally as an integer
  • Choosing the appropriate data type improves program efficiency and enables memory savings

5. Derived Data Types

What are Derived Data Types?

C language’s Derived Data Types are types used to combine basic data types to create more complex data structures. They are used to handle data structures that are difficult to express with only basic data types in a concise manner. The common derived data types include the following:
Data TypeDescription
ArrayStores multiple data items of the same type
struct (struct)Manages data of different types as a single unit
union (union)Data structure that shares memory
enum (enum)Defines meaningful constants
PointerStores memory addresses

1. Array

An array is a data structure that stores data of the same type in a contiguous memory region.

Array Declaration and Initialization

type array_name[size];
Example (integer array)
int numbers[5] = {10, 20, 30, 40, 50};
Accessing Array Elements
printf("%dn", numbers[0]);  // outputs 10
numbers[1] = 25;  // updates the second element

Multidimensional Arrays (2D Arrays)

int matrix[2][3] = {
    {1, 2, 3},
    {4, 5, 6}
};
Use Cases: bulk data management, matrix operations, buffer management, etc.

2. struct

A struct is a data type that can manage data of different types as a single unit.

Defining and Using Structs

struct Person {
    char name[50];
    int age;
    float height;
};

int main() {
    struct Person person1 = {"Taro", 25, 175.5};
    printf("Name: %s, Age: %d, Height: %.1f cmn", person1.name, person1.age, person1.height);
    return 0;
}
Use Cases: student data, product information, game character information, etc.

3. union

A union is a special data type that shares memory, allowing the same memory region to be used for different types.

Defining and Using Unions

union Data {
    int i;
    float f;
};

int main() {
    union Data data;
    data.i = 10;
    printf("Integer: %dn", data.i);

    data.f 3.14;
    printf("Float: %.2fn", data.f);  // at this point, the value of data.i becomes indeterminate

    return 0;
}
Use Cases: situations where memory savings are needed (e.g., managing different data formats with a single variable)

4. enum

An enum is a data type used to define meaningful constants.

Defining and Using Enums

enum Color { RED, GREEN, BLUE };

int() {
    enum Color favoriteColor = GREEN;
    printf("Favorite Color: %dn", favoriteColor); // 1 (GREEN is assigned 0 by default, then incremented)
    return 0;
}
Use Cases: state management (e.g., traffic light colors, days of the week, game statuses)

5. Pointer

A pointer is a special data type that stores the address of a variable.

Basics of Pointers

int a = 10;
int *ptr = &a;  // stores the address of 'a' in the pointer

printf("Address of a: %pn", &a);
printf("Pointer Value: %pn", ptr);
printf("Dereferenced Value: %dn", *ptr); // 10

Uses of Pointers

Dynamic memory management (malloc / free)Passing arrays to functionsString manipulation (char *str)

Summary

  • Arrays manage data of the same type together
  • Structs treat data of different types as a single unit
  • Unions are special data types that share memory
  • Enums define meaningful constants
  • Pointers handle variable addresses

6. Type Modifiers

What are type modifiers?

C language’stype modifiers (Type Modifiers) are keywords that modify the characteristics of basic data types. By using type modifiers appropriately, you can achieve memory optimization, data safety, and faster processing. The main type modifiers in C are listed below.
ModifierDescription
constVariable value cannot be changed (constant)
volatilePrevents optimization and forces the variable’s value to be fetched from memory each time
restrictImproves pointer optimization
signedInteger type that includes negative values (default)
unsignedInteger type that handles only non‑negative values

1. const (declare constants)

Using the const modifier makes it so that the variable’s value cannot be changed. This helps prevent incorrect assignments and improve code safety.

Example of using const

#include <stdio.h>

int main() {
    const int MAX_USERS = 100;  // declared as a constant
    printf("Max Users: %dn", MAX_USERS);

    // MAX_USERS = 200;  // Error change value because it's const

    return 0;
}

Applying const to function arguments

void printMessage(const char *message) {
    printf("%sn", message);
    // message[0] = 'H';  // Error! Cannot modify because it's const
}
Effect: Using const prevents data from being modified inside functions

2. volatile (prevent optimization)

volatile is used to prevent compiler optimizations. It is mainly used with hardware registers, global variables, and interrupt handlers.

Example of using volatile

#include <stdio.h>

volatile int flag = 0;  // Prevent optimization

int main() {
    while (flag == 0) {
        // Some processing (loop until flag changes)
    }
    printf("Flag changed!n");
    return 0;
}
Use cases:
  • Detecting variable changes in multithreaded processing
  • Reading hardware registers
  • Monitoring variables that may be changed by interrupt handlers

3. restrict (pointer optimization)

restrict is a qualifier introduced in C99 that guarantees that the memory region pointed to by one pointer is not shared with any other pointer. As a result, optimizations improve and processing can become faster.

Example of using restrict

#include <stdio.h>

void add_arrays(int *restrict a, int *restrict b, int *restrict result, int size) {
    for (int i = 0; i < size; i++) {
        result[i] = a[i] + b[i];
    }
}
Use cases:
  • Optimization of pointer arithmetic
  • Improved performance of numeric calculations
  • Vector operations (SIMD optimization)

4. signed and unsigned (signed and unsigned integers)

C integer types come in two varieties: signed and unsigned.
ModifierDescription
signedInteger that includes negative values (default)
unsignedInteger that includes only non‑negative values

Example of signed (signed integer)

int a = -10;  // can also store negative values
printf("%dn", a);  // prints -10

Example of unsigned (unsigned integer)

unsigned int b = 250;
printf("%un", b);  // prints 250

unsigned int c = -10;  // Error! Negative values cannot be stored
Use cases:
  • Counters that never use negative values (loop variables, etc.)
  • Processing binary data (bitwise operations)
  • Efficient use of memory size
Warning: Using unsigned prevents assigning negative values, so be careful of unintended overflow.
int x = -1;
unsigned int y = x;  // Error or unintended result

Summary

ModifierUseBenefit
constDeclare variables that cannot be changedPrevents incorrect modifications
volatilePrevents optimizationCorrectly obtains values from interrupt handlers and hardware registers
restrictPointer optimizationPrevents memory aliasing and enables fast processing
signedInteger type that includes negative valuesUseful for calculations involving negative numbers
unsignedInteger type that handles only positive valuesSaves memory and is suitable for counters and bitwise operations

7. Type Conversion (Casting)

What is Type Conversion?

In C, when performing operations or assignments between different data types, type conversion (Type Conversion) occurs. There are two kinds of type conversion: implicit conversion (automatic conversion) and explicit conversion (casting). If you don’t understand type conversion properly, data precision can be lost and unintended bugs can occur, so it’s important to use them correctly.

1. Implicit Type Conversion (Automatic Conversion)

In C, when performing operations or assignments between different data types, the compiler may automatically perform type conversion. This is called implicit conversion (Implicit Type Conversion).

Rules of Implicit Type Conversion

  • Small data type → larger data type is automatically converted
  • Integer type → floating-point type is converted
  • charint (treated as ASCII code)

Example of Implicit Type Conversion

#include <stdio.h>

int main() {
    int a = 10;
    float b = a;  // int → float automatic conversion
    printf("b: %.2fn", b);  // output: b: 10.00

    char letter = 'A';
    int asciiValue = letter;  // char → int conversion (ASCII code)
    printf("ASCII value of A: %dn", asciiValue);  // output: ASCII value of A: 65

    return 0;
}

2. Explicit Type Conversion (Casting)

Explicit conversion (Explicit Type Conversion) is where the developer intentionally converts the data type. This conversion is called casting (Casting).

Basic Syntax of Casting

(target data type) value or variable

Example of Using Casting

#include <stdio.h>

int main() {
    int a = 10, b = 3;
    float result = (float)a / b;  // convert int to float
    printf("Result: %.2fn", result);  // output: Result: 3.33

    return 0;
}
✅ By casting a with (float), you can prevent truncation caused by integer division.

3. Cases Where Casting Is Needed

(1) Integer Division

int a = 5, b = 2;
float result = a / b;  // result is 2 (integer division)
float correctResult = (float)a / b;  // correctly becomes 2.5
Point: If you cast at least one operand to float, the result will also be a float!

(2) Floating-point → Integer (fractional part truncation)

float pi = 3.14159;
int truncatedPi = (int)pi;  // becomes 3 (fractional part is truncated)
Note: Casting will truncate the fractional part!

(3) charint (convert character to ASCII code)

char letter = 'B';
int ascii = (int)letter;
printf("ASCII Code: %dn", ascii);  // output: ASCII Code: 66
✅ The char type is internally treated as an integer (ASCII code).

(4) Casting from void * (pointer)

Pointers can be handled generically using the void * type, but if you don’t cast to the appropriate type, it can cause malfunction.
void *ptr;
int num = 10;
ptr = &num;

int *intPtr = (int *)ptr;  // cast from void * to int *
printf("Value: %dn", *intPtr);  // output: Value: 10

4. Precautions for Type Conversion

(1) Data Precision Loss

When performing type conversion, there is a possibility of losing data precision.
float num = 3.9;
int rounded = (int)num;  // result: 3 (fractional part is truncated)
Solution: If you want rounding, use round()
#include <math.h>
int rounded = round(num);  // becomes 4

(2) Beware of conversions between unsigned and signed

unsigned int x = -1;
printf("%un", x);  // output: 4294967295 (32-bit environment)
Assigning a negative value to an unsigned type results in unexpected behavior!

(3) Converting from larger to smaller type (risk of overflow)

long bigNum = 100000;
short smallNum = (short)bigNum;  // data may not be stored correctly
Solution: Check data size with sizeof() beforehand
printf("Size of short: %lu bytesn", sizeof(short));

Summary

Type Conversion KindDescriptionExample
Implicit Type ConversionCompiler automatically converts the typeint → float
Explicit Type Conversion (Casting)Developer intentionally converts the type(float)a / b
Integer DivisionWhen int / int, the fraction is truncated(float)5 / 2 → 2.5
Floating-point → IntegerFractional part is truncated(int)3.9 → 3
Pointer CastingConvert void * to the appropriate type(int *)ptr
By mastering type conversion, you can write safe and less buggy programs.

8. Variable Scope and Lifetime

What is Variable Scope (Effective Range)?

C language, the variable scope (Scope) indicates where the variable can be referenced (effective range). Scope influences program design, and if not managed properly, can cause unintended behavior and bugs.

Types of Variable Scopes in C

Scope TypeDescriptionEffective Range
Local VariableOnly usable within a functionWithin the declared function or block
Global VariableUsable throughout the entire programThe entire program
Block ScopeValid only inside {}Within the declared block
File ScopeNot accessible from other filesWithin the defining file

1. Local Variables (Local Variables)

Local variables are declared inside a function or block {}, and are valid only within that function.

Example of Local Variable Usage

#include <stdio.h>

void myFunction() {
    int localVar = 10;  // local variable
    printf("Local variable: %dn", localVar);
}

int main() {
    myFunction();
    // printf("%d", localVar);  // Error! Local variable cannot be accessed outside the function
    return 0;
}
Advantages:
  • Prevents impact between functions (high safety)
  • Memory savings (automatically released when the function ends)
Points to Note:
  • Cannot be accessed from outside the function
  • Reinitialized each time the function is called (data is not retained)

2. Global Variables (Global Variables)

Global variables are declared outside functions, and are accessible throughout the entire program.

Example of Global Variable Usage

#include <stdio.h>

int globalVar = 100;  // global variable

void myFunction() {
    printf("Global variable: %dn", globalVar);
}

int main() {
    myFunction();
    globalVar = 200;  // can be modified from anywhere
    printf("Updated global variable: %dn", globalVar);
    return 0;
}
Advantages:
  • Can retain values across the entire program
  • Can share data among multiple functions
Disadvantages:
  • Potential for unintended changes (source of bugs)
  • Continues to occupy memory
  • Makes modularization difficult
👉 Solution: Use static to limit global variables (explained in the next section)

3. Static Variables (Static Variables)

Adding static allows local variables to retain their values. Also, applying static to a global variable makes it valid only within that file.

Example of static (Retaining Local Variable)

#include <stdio.h>

void counter() {
    static int count = 0;  // static retains value
    count++;
    printf("Count: %dn", count);
}

int main() {
    counter();  // Output: Count: 1
    counter();  // Output: Count: 2
    counter();  // Output: Count: 3
    return 0;
}
Advantages:
  • Retains value each time the function is called
  • Memory management is simple
Disadvantages:
  • Memory is not released until the program terminates

Example of static (Restricting Global Variable)

static int fileVar = 100;  // valid only within this file
Facilitates modularization and improves safety

4. External Variables (Extern)

Using the extern keyword allows you to reference variables that reside in other files.

Example of extern

file1.c
#include <stdio.h>

int sharedVar = 50;  // global variable

void printSharedVar() {
    printf("Shared Variable: %dn", sharedVar);
}
file2.c
#include <stdio.h>

extern int sharedVar;  // references variable from file1.c

int main() {
    printf("Accessing sharedVar: %dn", sharedVar);
    return 0;
}
Advantages:
  • Other files
Disadvantages:
  • Dependency

5. Variable Lifetime (Lifetime)

The lifetime of a variable refers to the period during which the variable exists in memory.
Variable TypeLifetimeRelease Timing
Local VariableWhile the function is executingWhen the function ends
Global VariableThroughout the entire programWhen the program terminates
Static Variable (static)Throughout the entire programWhen the program terminates
Dynamic Memory Allocation (malloc)free() until calledfree() until called

Summary

Variable TypeScope (Effective Range)Lifetime
Local VariableOnly within the functionUntil the function ends
Global VariableEntire programWhen the program ends
Static Variable (static)Within the declared scopeAt program termination
External Variable (extern)Referable from other filesWithin the declared scope
By properly managing variable scope and lifetime, you can prevent wasteful memory usage and create programs with fewer bugs.

9. Practical Data Type Selection

Why Choosing Data Types Matters

In C, selecting the appropriate data type provides benefits such as memory optimization, ensuring computational accuracy, and improving performance. => In C, selecting the appropriate data type provides benefits such as memory optimization, ensuring computational accuracy, and improving performance. Choosing an unsuitable data type can lead to problems such as wasted memory, overflow, and data loss. => Choosing an unsuitable data type can lead to problems such as wasted memory, overflow, and data loss.

1. When You Want to Save Memory

In embedded systems or memory-constrained environments, it is important to choose the smallest possible data type. => In embedded systems or memory-constrained environments, it is important to choose the smallest possible data type.

Integer Memory Sizes and Selection

Data TypeMemory SizeRange (32-bit environment)
char1 byte-128 ~ 127
short2 bytes-32,768 ~ 32,767
int4 bytes-2,147,483,648 ~ 2,147,483,647
long4–8 bytesWider range than int
unsigned int4 bytes0 ~ 4,294,967,295

Memory Saving Example

short temperature;  // Use short to save memory
Applicable scenarios: sensor data, loop counters, variables handling small-range values ⚠ Note: Exceeding the range can cause overflow!

2. When Accuracy Is Needed

In situations where computational accuracy is critical, using double can prevent rounding errors. => In situations where computational accuracy is critical, using double can prevent rounding errors.

Choosing Floating-Point Types

Data TypeMemory SizeSignificant Digits
float4 bytesabout 6–7 digits
double8 bytesabout 15 digits
long double10–16 bytesabout 18+ digits

Example Ensuring Accuracy

double distance = 1234567.1234567;  // When high-precision calculation is needed
Applicable scenarios: scientific calculations, financial calculations, measurement data ⚠ Note: float has larger errors, so use double in accuracy-critical situations.

3. When Negative Values Are Not Used

Using unsigned can extend the positive range and improve memory efficiency. => Using unsigned can extend the positive range and improve memory efficiency.

Example When Negative Values Are Not Used

unsigned int score = 250;
Applicable scenarios: counters, size specifications, bit operations ⚠ Note: Since unsigned cannot hold negative values, be careful of unintended overflow.
int x = -1;
unsigned int y = x;  // Causes an error or unintended result

4. Data Types Suitable for Loop Counters

For loop counters, unsigned int is more suitable than int. => For loop counters, unsigned int is more suitable than int.
for (unsigned int i = 0; i < 1000; i++) {
    // Loop processing
}
Benefit: Because unsigned does not consider negative values, the code can be more easily optimized.

5. When Dealing With Characters

char can store only a single character, but for strings you need a char array. => char can store only a single character, but for strings you need a char array.
char letter = 'A';   // only one character
char str[] = "Hello";  // string
Applicable scenarios: single-character handling (char), string handling (char array)

6. Using Enums to Make Code Clearer

If you want to manage integer values with meaningful names, using enum improves readability. => If you want to manage integer values with meaningful names, using enum improves readability.
enum Color { RED, GREEN, BLUE };

enum Color favoriteColor = GREEN;
Applicable scenarios: state management (e.g., traffic light colors, days of the week, game states)

7. Using Pointers for Flexible Memory Management

When you need flexible control over where data is stored, use pointers. => When you need flexible control over where data is stored, use pointers.
int num = 10;
int *ptr = &num;
printf("Value: %dn", *ptr);  // 10
Applicable scenarios: dynamic memory management, processing large amounts of data

8. Choosing the Optimal Data Type (Summary)

Use CaseRecommended Data TypeReason
Loop Counterunsigned intNo negative numbers needed, easier to optimize
Small IntegershortSaves memory
High-Precision CalculationsdoubleLess error than float
Unsigned Dataunsigned intAllows a larger range
Character ProcessingcharStores single-character data
State ManagementenumImproves readability and reduces mistakes
Flexible Data ManagementpointerMakes memory management easier
✅ Summary of Points
  • If you need to save memory, use short or char
  • If accuracy is needed, choose double
  • If negative values are not needed, use unsigned
  • Use enum to improve readability
  • Using pointers enables flexible memory management
Choosing the right data type makes program optimization and safety improvements possible possible.

10. Summary

The Importance of Variables and Data Types in C

In C, Understanding variables and data types is the foundation of programming . By choosing appropriate data types, memory optimization, improved processing speed, and bug prevention become possible. In this article, we explained the following points in detail.

1. What is a Variable?

  • A variable is a box that stores data and holds values that can be changed within the program.
  • Variable declaration and initialization are required, and choosing the appropriate data type is important.
int age = 25;  // integer variable
float pi = 3.14;  // floating-point variable
char letter = 'A';  // character variable

2. Overview of C Data Types

  • Basic data types (integer, floating-point, character)
  • Derived data types (array, struct, union, enum, pointer)
  • By choosing appropriate data types, you can prevent memory waste and make the program more efficient.

3. Basic Data Types (Primitive Types)

Data TypeMemory SizeCharacteristics
int4 bytesInteger
float4 bytesCan handle fractions but low precision
double8 bytesHigh-precision floating-point
char1 byteStores a single character

4. Derived Data Types (Array, Struct, Union, Enum, Pointer)

  • Array → Stores multiple data items of the same type
  • Struct (struct) → Manages data of different types as a single unit
  • Union (union) → A special data type that shares memory
  • Enum (enum) → Defines meaningful constants
  • Pointer → Stores memory addresses, enabling flexible data management

5. Type Qualifiers

By using type qualifiers, you can modify the characteristics of data types.
QualifierDescription
constConstant (value cannot be changed)
volatilePrevents optimization (for hardware handling)
restrictPointer optimization
unsignedPositive values only
const int MAX_USERS = 100;  // value cannot be changed

6. Type Conversion (Casting)

When conversion between different data types is needed, Implicit conversion (automatic) and explicit conversion (cast) occur.
int a = 10;
float b = (float)a / 3;  // cast

7. Variable Scope and Lifetime

  • Local variable → Valid only within a function
  • Global variable → Valid throughout the program (but requires careful management)
  • static → Can retain its value, but scope is limited
  • extern → Allows a variable to be referenced from other files
static int counter = 0;  // local variable that retains its value

8. Practical Data Type Selection

Use CaseRecommended Data TypeReason
Loop counterunsigned intNo negative numbers needed, efficient
Small integershortSaves memory
High-precision calculationsdoubleLess error than float
State managementenumMore readable and reduces mistakes
Flexible data managementpointerSuitable for dynamic memory management

9. FAQ (Frequently Asked Questions)

Q1. What is the difference between int and long?

A: long can store a wider range of values than int. However, its size may vary depending on the environment.
long num = 1000000;

Q2. Which should be used, float or double?

A: Use double if precision is needed; use float if memory savings are needed.
double distance = 3.1415926535;

Q3. What changes when using unsigned?

A: unsigned does not handle negative values and can store larger positive values.
unsigned int positive = 250;

Q4. Can the char type be used as a number?

A: It can be used in integer arithmetic as an ASCII code.
char letter = 'A';
int ascii = (int)letter;  // 65

Q5. What are the benefits of using const?

A: It prevents accidental modification of values, improving safety.
const int MAX_VALUE = 100;

Summary

  • In C, choosing appropriate data types improves program quality
  • By leveraging type qualifiers and casts, you can write safe and efficient programs
  • Understanding scope and lifetime enables proper variable management
  • Knowing how to choose data types in practice allows for better code design
Master C data types and strive for efficient and bug‑free programs!
年収訴求