CodeToLive

Variables and Data Types in C

In C, variables are used to store data values. C is a statically typed language, meaning you must declare the type of a variable before using it. Variables are essential for storing and manipulating data in programs.

Declaring Variables

Variables in C are declared using the syntax: type variable_name;. You can also initialize a variable at the time of declaration.


int age = 25;  // Integer
float height = 5.9;  // Float
char name[] = "Alice";  // String
      

Common Data Types

C provides several built-in data types to represent different kinds of data:

Type Modifiers

Type modifiers like signed, unsigned, short, and long can be used to alter the range and behavior of data types.


unsigned int positiveNumber = 100;  // Only positive values
short int smallNumber = 32767;  // Smaller range
long int largeNumber = 2147483647;  // Larger range
      

Constants

Constants are fixed values that cannot be changed during program execution. They are declared using the const keyword.


const float PI = 3.14159;  // Constant value
      

Variable Scope

The scope of a variable determines where it can be accessed in a program. Variables can have:


#include <stdio.h>

int globalVar = 10;  // Global variable

void function() {
    int localVar = 20;  // Local variable
    printf("Local Variable: %d\n", localVar);
}

int main() {
    printf("Global Variable: %d\n", globalVar);
    function();
    return 0;
}
      

Example: Using Variables and Data Types


#include <stdio.h>

int main() {
    int age = 25;
    float height = 5.9;
    char name[] = "Alice";
    const float PI = 3.14159;

    printf("Name: %s\n", name);
    printf("Age: %d\n", age);
    printf("Height: %.2f\n", height);
    printf("Value of PI: %.5f\n", PI);

    return 0;
}
      

Best Practices

Next: Control Structures