C Language | Introduction to C | Variables and Data Types

Variables store values temporarily so that a program can reuse input and calculation results.

Declaring and Initializing Variables

A variable names a storage area in memory. The compiler maps the identifier to an address and allocates space according to its type.

type variable1, variable2, ...;

Identifiers may contain letters, digits, and underscores, but cannot begin with a digit or use a reserved keyword. C identifiers are case-sensitive.

Basic type specifiers

Type Description
char one byte
int an integer type suitable for the target system
float single-precision floating-point value
double double-precision floating-point value

Exact sizes other than char depend on the implementation. Use the compiler documentation or sizeof when a size matters.

Assign a value with =, or initialize it during declaration.

int iVariable1 , iVariable2;
iVariable1 = 10;

int iVariable3 = 100;

An uninitialized local variable has an indeterminate value.

Code 1

#include <stdio.h>

int main() {
 int iVariable1 = 10 , iVariable2;
 iVariable2 = 100;
 return 0;
}

Format Specifiers

printf() uses format specifiers that begin with %.

Format Argument type Output
%d, %i int decimal integer
%x, %X unsigned int hexadecimal integer
%c int character
%s char * string
%f double floating-point value
%e, %E double exponential notation
%g, %G double shorter floating-point notation
%% none percent sign

Code 2

#include <stdio.h>

int main() {
 int iVariable = 10;
 printf("iVariable = %d\n" , iVariable);
 return 0;
}

Combining Type Specifiers

Additional specifiers adjust a type’s range or characteristics.

Type Description
short int no wider than int
long int no narrower than int
long double no narrower than double

Use signed for signed values and unsigned for values that do not need a negative range.

Code 3

#include <stdio.h>

int main() {
 signed char chVariable = -1;
 unsigned char uchVariable = 255;
 printf("chVariable = %d\nuchVariable = %d\n" , chVariable , uchVariable);
 return 0;
}

Unsigned integer conversion is defined modulo the type’s range. Conversions to signed types outside their representable range depend on the implementation.