Table of Contents:
Run C programData TypeFormat specifier' vs "float vs doubleScientific NumbersMemory SizeExtended TypeType ConversionConstantsOperatorsArithmetic OperatorsAssignment OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsPrecedenceBooleanif…elseArrayStringString FunctionsMemory AddressPointers and ArraysPointer ArithmeticDouble PointerFunctionInline functionFunction PointerFileStructureStructures an pointersUniontypedefStructure paddingMemory ManagementAllocationAccessReallocationDeallocationErrorNULLError HandlingMacrosQuizWhat’s left?
Run C program
- Use an online C compiler like: https://www.programiz.com/c-programming/online-compiler/
- Install local compiler
For Windows:
- Install MSYS2: https://www.msys2.org/
- Install GCC via MSYS2
- Compile C into an executable program and execute it:
> gcc .\create_file.c -o create_file > .\create_file.exe
Data Type
Data Type | Size | Description | Example |
int | 2 or 4 bytes | Stores whole numbers, without decimals | 1 |
float | 4 bytes | Stores fractional numbers, containing one or more decimals. Sufficient for storing 6-7 decimal digits | 1.99 |
double | 8 bytes | Stores fractional numbers, containing one or more decimals. Sufficient for storing 15 decimal digits | 1.99 |
char | 1 byte | Stores a single character/letter/number, or ASCII values | 'A' |
Format specifier
%dor%i: Used for integers (int).
%f: Used for floating-point numbers (float).
%c: Used for single characters (char).
%lf: Used for double (long float) precision numbers.
%s: Used for strings (arrays of characters).
%p: Used for pointers.
Why do we need format specifiers?
So computers can clarify that the number
65 is a number instead of the character 'A' (based on ASCII encoding).' vs "
Single quotes are for one char:
char a = 'a'Double quotes are for multiple char:
char greet[] = "Hello"; , printf("%s", greet);float vs double
ㅤ | float | double |
Precision | 6 or 7 decimal digits | ~15 digits |
Scientific Numbers
35e3 ⇒ The sign
e or E means “times 10 to the power of”.Set how many digits be shown:
printf("%f\n", a); // 35000.000000 (default) printf("%.1f\n"); // 35000.0 printf("%.2f\n"); // 35000.00 printf("%.4f\n"); // 35000.0000
Round to Nearest, Ties to Even
For chopping decimal case:
- < 0.5: Rounds down.
printf("%.0lf", 19.4)outputs 19.
- > 0.5: Rounds up.
printf("%.0lf", 19.6)outputs 20.
- = 0.5: Ties to Even
printf("%.0lf", 2.5)outputs 2 (because 2 is even).printf("%.0lf", 3.5)outputs 4 (because 4 is even).printf("%.0lf", 4.5)outputs 4.
Memory Size
Data Type | Size |
int | 2 or 4 bytes |
float | 4 bytes |
double | 8 bytes |
char | 1 byte |
int main() { int myInt; float myFloat; double myDouble; char myChar; printf("%zu\n", sizeof myInt); // 4 printf("%zu\n", sizeof myFloat); // 4 printf("%zu\n", sizeof myDouble); // 8 printf("%zu\n", sizeof myChar); // 1 return 0; }
Format specifier
%zu is for receiving the unsigned integer type — size_t , which is returned by sizeof .Extended Type
unsigned, short, longType | Size* | Range (commonly) | Format Specifier |
short int | 2 bytes | -32,768 to 32,767 | %hd or %hi |
unsigned int | 2 or 4 bytes | 0 to 65,535 (2 bytes)
0 to 4,294,967,295 (4 bytes) | %u |
long int | 4 or 8 bytes | -2,147,483,648 to 2,147,483,647 (4 bytes)
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (8 bytes) | %ld or %li |
long long int | 8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | %lld |
unsigned long int | 4 or 8 bytes | 0 to 4,294,967,295 (4 bytes)
0 to 18,446,744,073,709,551,615 (8 bytes) | %lu |
unsigned long long int | 8 bytes | 0 to 18,446,744,073,709,551,615 | %llu |
long double | 8, 12, or 16 bytes | Implementation-dependent, but more precision than double | %Lf |
unsigned means the type can only store non-negative values (0 or up).*Note: The size of these types can differ between systems (for example, 2 or 4 bytes, or 4 or 8 bytes), depending on whether the computer is older or newer, 32-bit or 64-bit, and which compiler is used.
Memorization:
short and long will convert to format specifier h and l excepting two cases:unsigned intbeu
Lforlong double
Type Conversion
- Implicit conversion (automatically by compiler)
- Explicit conversion (manually)
Implicit conversion:
int main() { // int to float float myFloat = 9; printf("%f", myFloat); // 9.000000 // float to int int myInt = 9.999999; printf("%d", myInt); // 9 return 0; }
Bad conversion case:
int main() { float sum = 5 / 2; printf("%f", sum); // 2.000000 return 0; }
Expecting the
sum = 2.5 but get the 2.000000Explicit conversion:
int main() { float sum = (float)5 / 2; printf("%f", sum); return 0; }
Constants
int main() { // ✅ Good const int BIRTHYEAR = 1980; // ❌ Error: error: assignment of read-only variable 'BIRTHMONTH' const int BIRTHMONTH; BIRTHMONTH = 8; return 0; }
Operators
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Bitwise operators
Arithmetic Operators
Operator | Name | Description | Example |
+ | Addition | Adds together two values | x + y |
- | Subtraction | Subtracts one value from another | x - y |
* | Multiplication | Multiplies two values | x * y |
/ | Division | Divides one value by another | x / y |
% | Modulus | Returns the division remainder | x % y |
++ | Increment | Increases the value of a variable by 1 | ++x |
-- | Decrement | Decreases the value of a variable by 1 | --x |
Assignment Operators
Operator | Example | Same As |
= | x = 5 | ㅤ |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
%= | x %= 3 | x = x % 3 |
&= | x &= 3 | x = x & 3 |
|= | x |= 3 | x = x | 3 |
^= | x ^= 3 | x = x ^ 3 |
>>= | x >>= 3 | x = x >> 3 |
<<= | x <<= 3 | x = x << 3 |
Comparison Operators
Operator | Name | Example | Description |
== | Equal to | x == y | Returns 1 if the values are equal |
!= | Not equal | x != y | Returns 1 if the values are not equal |
> | Greater than | x > y | Returns 1 if the first value is greater than the second value |
< | Less than | x < y | Returns 1 if the first value is less than the second value |
>= | Greater than or equal to | x >= y | Returns 1 if the first value is greater than, or equal to, the second value |
<= | Less than or equal to | x <= y | Returns 1 if the first value is less than, or equal to, the second value |
Logical Operators
Operator | Name | Example | Description |
&& | AND | x < 5 && x < 10 | Returns 1 if both statements are true |
|| | OR | x < 5 || x < 4 | Returns 1 if one of the statements is true |
! | NOT | !(x < 5 && x < 10) | Reverse the result, returns 0 if the result is 1 |
Bitwise Operators
Operator | Name | Description |
& | AND | Sets each bit to 1 if both bits are 1 |
| | OR | Sets each bit to 1 if at least one of the bits is 1 |
^ | XOR | Sets each bit to 1 if only one of the bits is 1 |
~ | NOT | Inverts all the bits |
<< | Left Shift | Shifts bits to the left (multiplies by powers of 2) |
>> | Right Shift | Shifts bits to the right (divides by powers of 2) |
Note: Bitwise operators only work on integer types( such as
int , char , or long)Example:
int main() { int a = 6; // Binary: 0110 int b = 3; // Binary: 0011 printf("%d\n", a & b); // Binary: 0010 Decimal: 2 printf("%d\n", a | b); // Binary: 0111 Decimal: 7 printf("%d\n", a ^ b); // Binary: 0101 Decimal: 5 printf("%d\n", ~a); //Binary: 1001 Decimal: -7 printf("%d\n", a << 1); // Binary: 1100 Decimal: 12 printf("%d\n", a >> 1); // Binary: 0011 Decimal: 3 return 0; }
Precedence
Precedence of common operators:
() : Parenthesis*, /, %: Multiplication, Division, Modulus+, -: Addition, Subtraction>, <, >=, <=: Comparison==, != : Equality&&: Logical AND||: Logical OR=: AssignmentBoolean
boolean is not a built-in data type, so importing the header file is required:#include <stdio.h> #include <stdbool.h> int main() { bool a = true; printf("%i", a); // 1 return 0; }
The
boolean value returns integer:1( or any other numbers doesn’t equal0) representstrue
0representsfalse
if…else
if is case-sensitive, so that If , IF , or iF will throw an error.Ternary operator:
variable = (condition) ? expressionTrue : expressionFalse;
Example:
int time = 20; (time < 18) ? printf("Good day.") : printf("Good evening.");
Array
Two ways to create an array:
#include <stdio.h> int main() { // First: create and assign values together. int myNumbers[] = { 1, 2, 3 }; printf("%i\n", myNumbers[0]); // Second: declare and then assign values. float myFloats[4]; myFloats[0] = 1.1; myFloats[1] = 1.2; myFloats[2] = 1.3; myFloats[3] = 1.4; printf("%.1f\n", myFloats[1]); return 0; }
The size of the array can’t be changed dynamically after creation.
Get the memory size:
int myNumbers[] = { 1, 2, 3 }; printf("%zu", sizeof(myNumbers)); // 12
3 elements 4 bytes = 12 bytes
Get the numbers of elements:
printf("%zu\n", sizeof(myNumbers) / sizeof(myNumbers[0])); //3
String
C does not support string type. Use an array of char type to create a string:
#include <stdio.h> int main() { char myString[] = "Hello World!"; printf("%s\n", myString); // Hello World! return 0; }
Another way to create a string:
#include <stdio.h> int main() { char myString[] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0'}; printf("%s\n", myString); return 0; }
\0 should be added in this way, while the first way will be added automatically. It is known as the “null-terminating character” in order to tell the C compiler it is the end of a string.Two ways are same:
#include <stdio.h> int main() { char myString1[] = "Hello World!"; char myString2[] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\0'}; printf("%zu\n", sizeof(myString1)); // 13 = "Hello World!" + "\0" printf("%zu\n", sizeof(myString2)); // 13 printf("%zu\n", sizeof(myString1) / sizeof(myString1[0])); // 13 printf("%zu\n", sizeof(myString2) / sizeof(myString2[0])); // 13 return 0; }
Attention that the return of
sizeof will include \0.String Functions
strlen: get the actual number of elements except \0.#include <stdio.h> #include <string.h> int main() { // 1. Except \0 char myString[] = "Hello World!"; printf("%zu\n", strlen(myString)); // 12 printf("%zu\n", sizeof(myString)); // 13 // 2. Actual length char alphabet[50] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; printf("%zu\n", strlen(alphabet)); // 26 printf("%zu\n", sizeof(alphabet)); // 50 return 0; }
strcat: concatenate string.#include <stdio.h> #include <string.h> int main() { char string1[20] = "Hello "; char string2[] = "World!"; // result is stored in string1 strcat(string1, string2); printf("%s\n", string1); // Hello World! return 0; }
Memory Address
The memory address is the location (a hexadecimal number starting with
0x) where a variable is stored on the computer:int myNum = 1; printf("%p", &myNum); // 0x7fff1bf8340c
&: reference operator
&myNum: pointer
%p: format specifier
The
* can do two things:- Create a pointer variable
- Get the value of a variable the pointer points to (dereference operator).
int myNum = 1; // 1. Create a pointer variable int* myNumPointer = &myNum; printf("%p\n", &myNum); // 0x7fff1bf8340c printf("%p\n", myNumPointer); // 0x7ffcc1cdb674 // 2. Get the value printf("%i", *myNumPointer); // 1
Good to know. The following two ways are the same:
int* myNumPointer = &myNum; int *myNumPointer = &myNum;
Pointers and Arrays
The array variable is a pointer pointing to the first element:
int myNumbers[4] = { 25, 50, 75, 100}; printf("%p\n", &myNumbers); // 0x7ffe90f37250 printf("%p\n", &myNumbers[0]); // 0x7ffe90f37250
So:
printf("%i\n", myNumbers[0]); // 25 printf("%i\n", *myNumbers); // 25 printf("%i\n", myNumbers[1]); // 50 printf("%i\n", *(myNumbers + 1)); // 50 printf("%i\n", myNumbers[2]); // 75 printf("%i\n", *(myNumbers + 2)); // 75 printf("%i\n", myNumbers[3]); // 100 printf("%i\n", *(myNumbers + 3)); // 100 // === Above equals to === for (int i = 0; i < 4; i++) { printf("%d\n", *(myNumbers + i)); }
Change value by pointer:
int myNumbers[4] = { 25, 50, 75, 100}; *myNumbers = 13; *(myNumbers + 1) = 27; for (int i = 0; i < 4; i++) { printf("%d\n", *(myNumbers + i)); }
Pointer Arithmetic
Pointer arithmetic means changing the pointer to point to a different memory address.
int myNumbers[4] = { 25, 50, 75, 100}; int *ptr = myNumbers; for (int i = 0; i < 4; i++) { printf("%d\n", *(myNumbers + i)); printf("%d\n", *ptr); ptr++; } /* 25 25 50 50 75 75 100 100 */
The moving step depends on the data type:
int*moves 4 bytes.
char*moves 1 byte.
Double Pointer
int myNum = 10; int *ptr = &myNum; int **pptr = &ptr; printf("myNum = %d\n", myNum); printf("ptr = %p\n", ptr); printf("*ptr = %d\n", *ptr); printf("pptr = %p\n", pptr); printf("**pptr = %i\n", **pptr);
Function
Pass an array as parameters:
int printArray(int arr[5]) { for(int i = 0; i < 5; i++) { printf("arr[%d] = %i\n", i, *(arr + i)); } } int main() { int myArray[5] = { 5, 10, 15, 20, 25}; printArray(myArray); return 0; }
Function declaration, definition, and call:
// Function declaration void myFunction(); // The main method int main() { myFunction(); // call the function return 0; } // Function definition void myFunction() { printf("I just got executed!"); }
Inline function
Inline function: copy the function code to the place where calls it.
Regular Function:
int square(int x) { return x * x; }
Inline Function:
inline int square(int x) { return x * x; }
Both functions work the same way. The only difference is that the
inline version suggests to the compiler to copy the function's code directly where it is used.
Regular Function | Inline Function |
Code jumps to the function each time it's called | Code is inserted directly where it's called |
Slightly slower (small delay) | Slightly faster |
Good for large functions | Good for small functions |
Function Pointer
Declare a function pointer:
// returnType (*pointerName)(parameterType1, parameterType2, ...) int (*ptr)(int, int);
Two ways to assign:
ptr = add; ptr = &add;
Two ways to call function:
ptr(5, 3); (*ptr)(5, 3);
A callback function: a function pointer passed to another function as a parameter.
#include <stdio.h> void greetMorning() { printf("Good Morning!\n"); } void greetEvening() { printf("Good Evening!\n"); } void greet(void (*func)()) { func(); } int main() { greet(greetMorning); greet(greetEvening); return 0; }
Normal Function | Function Pointer |
Called directly by its name | Called using a pointer |
The function is decided before the program runs | You can choose which function to call while the program is running |
Good for simple code | Good for flexible and reusable code |
File
Create a file:
#include <stdio.h> int main() { FILE *fptr; printf("Start to create a file\n"); fptr = fopen("test.txt", "w"); printf("Close the file\n"); fclose(fptr); }
w- Writes to a file
a- Appends new data to a file
r- Reads from a file
Write a file:
#include <stdio.h> int main() { FILE *fptr; printf("Open test.txt file\n"); fptr = fopen("test.txt", "w"); printf("Write some text to the file\n"); fprintf(fptr, "Some text"); printf("Close the file\n"); fclose(fptr); return 0; }
Read the file:
#include <stdio.h> int main() { FILE *fptr; printf("Open a file in read mode\n"); fptr = fopen("test.txt", "r"); printf("Create a string to store the content\n"); char content[100]; printf("Read the content and store to the string\n"); fgets(content, 100, fptr); printf("Show the content: %s\n", content); printf("Close the file"); fclose(fptr); return 0; }
Improve the program:
- Return if the file doesn’t exist.
fgetsonly reads one line; add loop to it.
#include <stdio.h> int main() { FILE *fptr; printf("Open a file in read mode\n"); fptr = fopen("test.txt", "r"); if (fptr == NULL) { printf("The file doesn't exist"); return 0; } printf("Create a string to store the content\n"); char content[100]; printf("Read the content and store to the string\n"); // fgets(content, 100, fptr); printf("Show the content:\n"); while(fgets(content, 100, fptr)) { printf("%s\n", content); } printf("Close the file"); fclose(fptr); return 0; }
Structure
Structure: a way to store multiple values of different data types.
#include <stdio.h> #include <string.h> // Create a structure: struct Car { char brand[10]; int year; }; int main() { // Create structure variables: struct Car c1 = {"Toyota", 2020}; struct Car c2; // Copy a structure: c2 = c1; // Assign new value: c2.year = 1999; strcpy(c2.brand, "BMW"); // Special way to assign an string printf("%s %d\n", c1.brand, c1.year); // Toyota 2020 printf("%s %i\n", c2.brand, c2.year); // BMW 1999 }
Structures an pointers
Define a structure pointer:
#include <stdio.h> #include <string.h> struct Car { char brand[10]; int year; }; int main() { struct Car c = {"Toyota", 2020}; struct Car *ptr = &c; ptr->year = 1999; strcpy(ptr->brand, "BMW"); printf("%s\n", ptr->brand); printf("%i\n", ptr->year); }
A structure pointer uses
-> to access members.Union
A union is similar to a structure, but the difference is:
- In a
struct, each member has its own memory.
- In a
union, all members share the same memory, which means you can only use one of the values at a time.
The size of a union = the size of the largest member:
#include <stdio.h> union myUnion { int myNum; char myString[36]; }; int main() { union myUnion u1; printf("Size of union: %zu bytes\n", sizeof(u1)); return 0; }
typedef
typedef: set an alias for an existing type.#include <stdio.h> int main() { typedef float Temperature; Temperature today = 25.5; Temperature tomorrow = 30; printf("Today: %.1f C\n", today); // Today: 25.5 C printf("Tomorrow: %.1f C\n", tomorrow); // Tomorrow: 30.0 C return 0; }
Make the structure definition more readable:
#include <stdio.h> //Without typedef struct Car { char brand[30]; int year; }; // With typedef typedef struct { char brand[30]; int year; } Car; int main() { struct Car car1 = { "BMW", 1999 }; Car car2 = { "Ford", 1969 }; printf("%s, %d\n", car1.brand, car1.year); printf("%s, %d\n", car2.brand, car2.year); return 0; }
Structure padding
C compiler may add some extra data padding to the structure to align memory in order to improve CPU read performance.
#include <stdio.h> struct Example1 { char a; // 1 byte int b; // 4 bytes char c; // 1 byte }; struct Example2 { int b; // 4 bytes char a; // 1 byte char c; // 1 byte }; int main() { printf("Size of struct: %zu bytes\n", sizeof(struct Example1)); // Size of struct: 12 bytes printf("Size of struct: %zu bytes\n", sizeof(struct Example2)); // Size of struct: 8 bytes return 0; }
Memory Management
Allocation
Allocation: the process of reversing memory.
Two types of memory:
- Static memory: reserves memory before the program runs
- Dynamic memory: reserves memory after the program starts running, also called runtime memory
- Stack memory: a type of dynamic memory that is reserved for variables that are declared inside functions. Variables declared inside a function use stack memory rather than static memory.
Static memory allocation:
int students[20]; printf("%zu", sizeof(students)); // 80 bytes
Dynamic memory allocation:
int *ptr1 = malloc(size); int *ptr2 = calloc(amount, size);
malloc = memory allocation calloc = contiguous allocation
#include <stdio.h> #include <stdlib.h> int main() { int *students; int studentNum = 12; students = calloc(studentNum, sizeof(*students)); printf("%d bytes\n", studentNum * sizeof(*students)); // 48 bytes return 0; }
Access
Access dynamic memory like string:
#include <stdio.h> #include <stdlib.h> int main() { // Allocate memory int *ptr; ptr = calloc(4, sizeof(*ptr)); // Write to the memory *ptr = 10; // Same to `ptr[0]` ptr[1] = 20; ptr[2] = 30; // Read from the memory printf("%d\n", *ptr); // 10 printf("%d %d %d", ptr[1], ptr[2], ptr[3]); //20 30 0 return 0; }
Reallocation
// Online C compiler (editor) // Write and run C online using this editor. #include <stdio.h> #include <stdlib.h> int main() { // Allocate memory int *ptr1 = calloc(4, sizeof(*ptr1)); // Write to the memory *ptr1 = 10; // One way to access the first element; another way is ptr[0] ptr1[1] = 20; ptr1[2] = 30; // Read from the memory printf("%p\n", ptr1); // 0x1c3732a0 printf("%d\n", *ptr1); // 10 printf("%d %d %d\n", ptr1[1], ptr1[2], ptr1[3]); // 20 30 0 int *ptr2 = realloc(ptr1, 1000); if (ptr2 == NULL) { printf("ptr2 reallocation have failed"); } else { printf("%p\n", ptr2); // 0x1c3736d0 printf("%d\n", *ptr2); // 10 printf("%d %d %d\n", ptr2[1], ptr2[2], ptr2[3]); // 20 30 0 } return 0; }
if
int *ptr2 = realloc(ptr1, 1E18) then the programm will print: ptr2 reallocation have failedDeallocation
int *ptr; ptr = malloc(sizeof(*ptr)); free(ptr); ptr = NULL;
Error
NULL
NULL is a special value that represents an “empty pointer”.Error Handling
C does not have built-in exception handling(like try/catch) instead use:
- Return value
- Global error codes
- Helper functions like
perror()andstrerro()
perror:int main() { FILE *f = fopen("nothing.txt", "r"); if (f == NULL) { perror("Error opening file"); // Error opening file: No such file or directory return 1; } fclose(f); return 0; }
strerror() and errno :errno(error number): a global variable that stores the error code from the last failed operation.strerro(string error): a function to convert theerrnointo a readable message.
#include <stdio.h> #include <errno.h> #include <string.h> int main() { FILE *f = fopen("nothing.txt", "r"); if (f == NULL) { printf("Error: %s\n", strerror(errno)); // ERROR! // Error: No such file or directory return 1; } fclose(f); return 0; }
Error constants are defined in
<errno.h>. You can compare errno to them to detect specific issuesError Code | Meaning |
ENOENT | No such file or directory |
EACCES | Permission denied |
ENOMEM | Not enough memory |
EINVAL | Invalid argument |
Using
exit() to stop program:0represents success.
- Non-zero values (like
1orEXIT_FAILURE) indicate errors
Common Exit Status Codes
Code | Meaning |
0 | Success - the program completed normally |
1 | Error - something went wrong |
EXIT_SUCCESS | Same as 0 (defined in <stdlib.h>) |
EXIT_FAILURE | Same as a non-zero error code (also in <stdlib.h>) |
Macros
Before the compilation run, the preprocessor will trigger to define macros and include files, etc.
Preprocessor commands begin with a
# symbol and are called directives. The most common directive is #include.#definecreates a macro.
#ifdefand#ifndef- Conditional Compilation
#include <stdio.h> #define DEBUG int main() { #ifdef DEBUG printf("Debug mode is on"); #endif #ifndef DEBUG printf("Debug mode is off"); #endif return 0; }
Quiz
When a variable is created in C, a memory address is assigned to the variable. Is it true?
What’s left?
I have learned the C language through W3CSchool. I think that most content will be forgotten after a period of time. So I want to grasp the core content, concepts, or principles of the C language. Can you guide me on these?
