0
0
C++programming~5 mins

Type modifiers in C++

Choose your learning style9 modes available
Introduction

Type modifiers change the meaning of a basic data type to better fit what you want to store.

When you want to store only positive numbers using <code>unsigned</code>.
When you need a variable that cannot be changed after setting it using <code>const</code>.
When you want to use a smaller or larger version of a type using <code>short</code> or <code>long</code>.
When you want to make sure a variable is stored in memory and not optimized away using <code>volatile</code>.
When you want to tell the compiler a variable can change unexpectedly, like hardware registers, using <code>volatile</code>.
Syntax
C++
type_modifier basic_type variable_name;

You can combine some modifiers, like const unsigned int.

Modifiers change how the computer treats the data but keep the same basic type.

Examples
Stores only positive integers (including zero).
C++
unsigned int age;
Value cannot be changed after setting it.
C++
const float pi = 3.14f;
Stores a very large integer number.
C++
long long distance;
Tells the compiler this value can change anytime, like from hardware.
C++
volatile int sensorValue;
Sample Program

This program shows different type modifiers in action. It prints values stored in variables with modifiers.

C++
#include <iostream>

int main() {
    unsigned int positiveNumber = 100;
    const int fixedValue = 50;
    long long bigNumber = 10000000000LL;
    volatile int sensor = 5;

    std::cout << "Positive number: " << positiveNumber << "\n";
    std::cout << "Fixed value: " << fixedValue << "\n";
    std::cout << "Big number: " << bigNumber << "\n";
    std::cout << "Sensor value: " << sensor << "\n";

    // fixedValue = 60; // This would cause an error because fixedValue is const

    return 0;
}
OutputSuccess
Important Notes

const variables must be initialized when declared.

unsigned types cannot hold negative numbers.

volatile is mostly used in special cases like hardware programming.

Summary

Type modifiers change how basic types behave.

Common modifiers include const, unsigned, long, short, and volatile.

Use them to better match your data needs and program safety.