C provides several built-in types. Common numeric types include:
int a = 10; // typically 4 bytes
long b = 100000L; // typically 8 bytes
float c = 3.14f; // single-precision floating point
double d = 3.14159; // double-precision floating point
Use sizeof()
to check the exact size on your
platform.
A function consists of a return type, name, parameters, and a body:
int add(int x, int y) {
return x + y;
}
Usage:
int result = add(2, 3); // result = 5
Variables must be declared with a type:
int count = 42;
float ratio = 0.75;
Uninitialized variables contain garbage values.
Expressions involve operators and operands:
int a = 5, b = 3;
int sum = a + b;
int product = a * b;
float quotient = (float)a / b;
C has standard arithmetic and logical operators.
A pointer stores the address of another variable:
int x = 10;
int *p = &x; // p points to x
*p = 20; // x is now 20
Arrays are contiguous blocks of elements:
int arr[3] = {1, 2, 3};
int first = arr[0];
Arrays and pointers are closely related:
int *ptr = arr;
("%d\n", ptr[1]); // prints 2 printf
if
StatementsConditional execution:
int x = 10;
if (x > 0) {
("Positive\n");
printf} else if (x == 0) {
("Zero\n");
printf} else {
("Negative\n");
printf}
while
StatementsLoop while condition is true:
int i = 0;
while (i < 5) {
("%d\n", i);
printf++;
i}
for
StatementsMore compact loop syntax:
for (int i = 0; i < 5; i++) {
("%d\n", i);
printf}
typedef struct
DefinitionsCustom types using struct
and typedef
:
typedef struct {
int id;
float grade;
} Student;
= {123, 95.5};
Student s ("ID: %d, Grade: %.1f\n", s.id, s.grade); printf
You can also use the traditional style:
struct Student {
int id;
float grade;
};