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:
- int: Represents whole numbers (e.g.,
10,-5). - float: Represents decimal numbers (e.g.,
3.14,-0.001). - char: Represents single characters (e.g.,
'A','b'). - double: Represents double-precision floating-point numbers (e.g.,
3.1415926535). - void: Represents the absence of type, often used in functions that return no value.
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:
- Local Scope: Variables declared inside a function are local to that function.
- Global Scope: Variables declared outside all functions are global and can be accessed anywhere in the program.
#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
- Use Descriptive Names: Choose meaningful names for variables to improve code readability.
- Initialize Variables: Always initialize variables to avoid undefined behavior.
- Use Constants: Use
constfor values that should not change. - Limit Scope: Declare variables in the smallest scope possible to avoid unintended side effects.