Variables in C
Variables in C
Variables are like labels for storage locations in memory where we can store data. Each variable has:
Type: What kind of data it holds (e.g., integers, floats, characters).
Name: The identifier you give to access that value (like a tag).
Value: The actual data stored in the variable.
Declaring Variables:
Before using a variable in C, you must declare it (tell the compiler what type it will hold). The syntax looks like this:
Type: Specifies the kind of data the variable can store.
Variable Name: A unique name to identify the variable.
Examples:
2. Initialization
You can also declare and assign a value to a variable in one step. This is called initialization:
If you don’t initialize a variable, it contains garbage values, meaning random values from memory.
3. Naming Variables
In C, there are some rules and conventions for naming variables:
Rules:
Must begin with a letter (a-z, A-Z) or an underscore (
_
), not a number.After the first character, you can use numbers (e.g.,
score1
is valid).Can’t use C keywords like
int
,float
,return
as variable names.
Conventions:
Variable names should be meaningful and self-explanatory. Instead of
x
, useage
orheight
.Use lowercase for variables, e.g.,
student_age
, and uppercase for constants.
4. Scope of Variables
Variables in C have different scopes, meaning where they can be accessed. The two main types are:
Local Variables: Declared inside a function, accessible only within that function.
Global Variables: Declared outside all functions, accessible from anywhere in the program.
Example of local variable:
Example of global variable:
5. Constant Variables
Sometimes, you don’t want a variable’s value to change. For that, we use the keyword const
to make a variable constant.
Example:
Now, DAYS_IN_WEEK
is fixed to 7, and trying to change it later in the code will cause a compilation error.
6. Memory and Variable Sizes
Each data type takes up a certain amount of memory. The size of the variable depends on its data type and the system architecture (32-bit or 64-bit).
Here’s a typical size chart for common data types (on a 32-bit system):
int
: 4 bytesfloat
: 4 bytesdouble
: 8 byteschar
: 1 byte
You can check the size of any variable using the sizeof()
function.
Example:
7. More on Data Types
int
: Holds integer values, both positive and negative (e.g.,int x = -10;
)float
: Used for single-precision floating-point numbers (e.g.,float x = 3.14;
)double
: Used for double-precision floating-point numbers (e.g.,double x = 3.1415926535;
)char
: Used for single characters (e.g.,char letter = 'A';
), but it also stores ASCII values internally.
Unsigned Types:
For integers, you can declare unsigned versions of the type, which can only store positive numbers but offer a larger positive range.
Last updated
Was this helpful?