936 lines
15 KiB
Markdown
Raw Normal View History

2025-11-22 23:28:28 +01:00
# RC Programming Language Tutorial
Complete guide to the RC (Retoor's C) programming language - a C-like interpreted language with enhanced string manipulation capabilities.
## Table of Contents
1. [Basic Program Structure](#basic-program-structure)
2. [Data Types](#data-types)
3. [Variables and Declarations](#variables-and-declarations)
4. [Arrays](#arrays)
5. [Operators](#operators)
6. [Control Flow](#control-flow)
7. [Functions](#functions)
8. [Pointers](#pointers)
9. [Output with printf](#output-with-printf)
10. [String Operations](#string-operations)
11. [String Slicing](#string-slicing)
12. [Math Functions](#math-functions)
13. [String Manipulation Functions](#string-manipulation-functions)
14. [Socket Programming](#socket-programming)
15. [Comments](#comments)
---
## Basic Program Structure
Every RC program must have a `main` function that returns an integer.
```c
int main() {
printf("Hello, World!\n");
return 0;
}
```
## Data Types
RC supports two primary data types:
### Integer (int)
```c
int x = 42;
int y = -10;
int z; // Uninitialized variable
```
### Character Pointer (char*)
Used for strings.
```c
char *name = "Alice";
char *message = "Hello, World!";
char *empty = "";
```
## Variables and Declarations
### Variable Declaration
```c
int main() {
int age = 25;
int count;
count = 10;
char *name = "Bob";
char *greeting;
greeting = "Hi there!";
return 0;
}
```
### Multiple Variables
```c
int main() {
int a = 1, b = 2, c = 3;
char *first = "Hello", *second = "World";
printf("a=%d, b=%d, c=%d\n", a, b, c);
return 0;
}
```
## Arrays
### Integer Arrays
```c
int main() {
int numbers[5];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
printf("First: %d\n", numbers[0]);
printf("Second: %d\n", numbers[1]);
return 0;
}
```
### Character Arrays (Buffers)
```c
int main() {
char buffer[100];
int i = 0;
buffer[0] = 65; // ASCII 'A'
buffer[1] = 66; // ASCII 'B'
buffer[2] = 0; // Null terminator
return 0;
}
```
## Operators
### Arithmetic Operators
```c
int main() {
int a = 10;
int b = 3;
printf("Addition: %d\n", a + b); // 13
printf("Subtraction: %d\n", a - b); // 7
printf("Multiplication: %d\n", a * b); // 30
printf("Division: %d\n", a / b); // 3
return 0;
}
```
### Comparison Operators
```c
int main() {
int x = 5;
int y = 10;
if (x == y) printf("Equal\n");
if (x != y) printf("Not equal\n");
if (x < y) printf("Less than\n");
if (x > y) printf("Greater than\n");
if (x <= y) printf("Less or equal\n");
if (x >= y) printf("Greater or equal\n");
return 0;
}
```
### Logical Operators
```c
int main() {
int a = 1;
int b = 0;
if (a && b) printf("Both true\n");
if (a || b) printf("At least one true\n");
return 0;
}
```
### Unary Operators
```c
int main() {
int x = 10;
int y = -x; // Negation
printf("x = %d\n", x); // 10
printf("y = %d\n", y); // -10
return 0;
}
```
## Control Flow
### If-Else Statements
```c
int main() {
int age = 18;
if (age >= 18) {
printf("Adult\n");
} else {
printf("Minor\n");
}
return 0;
}
```
### Nested If-Else
```c
int main() {
int score = 85;
if (score >= 90) {
printf("Grade: A\n");
} else if (score >= 80) {
printf("Grade: B\n");
} else if (score >= 70) {
printf("Grade: C\n");
} else {
printf("Grade: F\n");
}
return 0;
}
```
### While Loops
```c
int main() {
int i = 0;
while (i < 5) {
printf("Count: %d\n", i);
i = i + 1;
}
return 0;
}
```
### Infinite Loops with Break Condition
```c
int main() {
int counter = 0;
while (1) {
printf("Iteration: %d\n", counter);
counter = counter + 1;
if (counter == 10) {
printf("Breaking loop\n");
return 0;
}
}
return 0;
}
```
## Functions
### Function Definition
```c
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(5, 3);
printf("Result: %d\n", result);
return 0;
}
```
### Function with No Parameters
```c
int get_constant() {
return 42;
}
int main() {
int value = get_constant();
printf("Value: %d\n", value);
return 0;
}
```
### Recursive Functions
```c
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
printf("5! = %d\n", factorial(5)); // 120
return 0;
}
```
### Functions Returning Strings
```c
char *get_greeting() {
return "Hello, RC!";
}
int main() {
char *message = get_greeting();
printf("%s\n", message);
return 0;
}
```
## Pointers
### Address-of Operator (&)
```c
int main() {
int x = 42;
int addr = &x; // Get address of x
printf("Value: %d\n", x);
printf("Address: %d\n", addr);
return 0;
}
```
### Dereference Operator (*)
```c
int main() {
int x = 42;
int addr = &x;
int value = *addr; // Dereference to get value
printf("Original: %d\n", x);
printf("Via pointer: %d\n", value);
return 0;
}
```
### Pointer Assignment
```c
int main() {
int x = 10;
int addr = &x;
*addr = 20; // Modify x through pointer
printf("x is now: %d\n", x); // 20
return 0;
}
```
## Output with printf
### Basic Printf
```c
int main() {
printf("Hello, World!\n");
return 0;
}
```
### Printing Integers
```c
int main() {
int age = 25;
printf("Age: %d\n", age);
printf("Multiple: %d and %d\n", 10, 20);
return 0;
}
```
### Printing Strings
```c
int main() {
char *name = "Alice";
printf("Name: %s\n", name);
printf("Greeting: %s %s\n", "Hello", name);
return 0;
}
```
### Escape Sequences
```c
int main() {
printf("Line 1\nLine 2\n"); // Newline
printf("Tab\there\n"); // Note: Only \n is supported
return 0;
}
```
## String Operations
### String Concatenation with +
```c
int main() {
char *first = "Hello";
char *second = " World";
char *result = first + second;
printf("%s\n", result); // "Hello World"
return 0;
}
```
### Multiple Concatenation
```c
int main() {
char *a = "RC ";
char *b = "is ";
char *c = "awesome!";
char *message = a + b + c;
printf("%s\n", message); // "RC is awesome!"
return 0;
}
```
### Concatenation with Literals
```c
int main() {
char *name = "Alice";
char *greeting = "Hello, " + name + "!";
printf("%s\n", greeting); // "Hello, Alice!"
return 0;
}
```
## String Slicing
### Basic Slicing [start:end]
```c
int main() {
char *text = "Hello World";
char *first_word = text[0:5];
char *second_word = text[6:11];
printf("First: %s\n", first_word); // "Hello"
printf("Second: %s\n", second_word); // "World"
return 0;
}
```
### Slicing Examples
```c
int main() {
char *str = "Programming";
printf("First 4: %s\n", str[0:4]); // "Prog"
printf("Middle: %s\n", str[3:7]); // "gram"
printf("Last 4: %s\n", str[7:11]); // "ming"
return 0;
}
```
### Combining Slicing with Operations
```c
int main() {
char *text = "hello world";
char *uppercase = upper(text[0:5]);
printf("%s\n", uppercase); // "HELLO"
char *combined = text[0:5] + " " + text[6:11];
printf("%s\n", combined); // "hello world"
return 0;
}
```
## Math Functions
All math functions return integers (long). Floating-point values are truncated.
### sqrt(x) - Square Root
```c
int main() {
printf("sqrt(16) = %d\n", sqrt(16)); // 4
printf("sqrt(25) = %d\n", sqrt(25)); // 5
printf("sqrt(100) = %d\n", sqrt(100)); // 10
return 0;
}
```
### pow(base, exp) - Power
```c
int main() {
printf("2^3 = %d\n", pow(2, 3)); // 8
printf("10^2 = %d\n", pow(10, 2)); // 100
printf("5^4 = %d\n", pow(5, 4)); // 625
return 0;
}
```
### abs(x) - Absolute Value
```c
int main() {
printf("abs(-42) = %d\n", abs(-42)); // 42
printf("abs(42) = %d\n", abs(42)); // 42
printf("abs(0) = %d\n", abs(0)); // 0
return 0;
}
```
### Trigonometric Functions
Note: Results are scaled by 1,000,000 for precision.
```c
int main() {
int s = sin(0);
int c = cos(0);
int t = tan(0);
printf("sin(0) = %d\n", s);
printf("cos(0) = %d\n", c);
printf("tan(0) = %d\n", t);
return 0;
}
```
### floor(x) and ceil(x)
```c
int main() {
printf("floor(7) = %d\n", floor(7)); // 7
printf("ceil(7) = %d\n", ceil(7)); // 7
return 0;
}
```
## String Manipulation Functions
### strpos(haystack, needle) - Find Substring
```c
int main() {
char *text = "Hello World";
int pos1 = strpos(text, "World");
printf("Position of 'World': %d\n", pos1); // 6
int pos2 = strpos(text, "xyz");
printf("Position of 'xyz': %d\n", pos2); // -1 (not found)
return 0;
}
```
### substr(str, start, length) - Extract Substring
```c
int main() {
char *text = "Programming";
char *sub1 = substr(text, 0, 4);
printf("substr(0, 4): %s\n", sub1); // "Prog"
char *sub2 = substr(text, 3, 4);
printf("substr(3, 4): %s\n", sub2); // "gram"
return 0;
}
```
### upper(str) - Convert to Uppercase
```c
int main() {
char *text = "hello world";
char *upper_text = upper(text);
printf("Original: %s\n", text); // "hello world"
printf("Uppercase: %s\n", upper_text); // "HELLO WORLD"
return 0;
}
```
### lower(str) - Convert to Lowercase
```c
int main() {
char *text = "HELLO WORLD";
char *lower_text = lower(text);
printf("Original: %s\n", text); // "HELLO WORLD"
printf("Lowercase: %s\n", lower_text); // "hello world"
return 0;
}
```
### strip(str) - Remove Leading/Trailing Whitespace
```c
int main() {
char *text = " Hello World ";
char *stripped = strip(text);
printf("Original: '%s'\n", text); // " Hello World "
printf("Stripped: '%s'\n", stripped); // "Hello World"
return 0;
}
```
### replace(str, old, new) - Replace Substring
```c
int main() {
char *text = "Hello World";
char *replaced = replace(text, "World", "RC");
printf("Original: %s\n", text); // "Hello World"
printf("Replaced: %s\n", replaced); // "Hello RC"
return 0;
}
```
### Multiple Replacements
```c
int main() {
char *text = "foo bar foo";
char *replaced = replace(text, "foo", "baz");
printf("%s\n", replaced); // "baz bar baz"
return 0;
}
```
### startswith(str, prefix) - Check Prefix
```c
int main() {
char *text = "Hello World";
if (startswith(text, "Hello")) {
printf("Starts with 'Hello'\n");
}
if (startswith(text, "World")) {
printf("Starts with 'World'\n");
} else {
printf("Does not start with 'World'\n");
}
return 0;
}
```
### endswith(str, suffix) - Check Suffix
```c
int main() {
char *text = "Hello World";
if (endswith(text, "World")) {
printf("Ends with 'World'\n");
}
if (endswith(text, "Hello")) {
printf("Ends with 'Hello'\n");
} else {
printf("Does not end with 'Hello'\n");
}
return 0;
}
```
### strlen(str) - Get String Length
```c
int main() {
char *text = "Hello";
int len = strlen(text);
printf("Length of '%s': %d\n", text, len); // 5
return 0;
}
```
### Combining String Functions
```c
int main() {
char *text = " HELLO world ";
char *processed = upper(strip(text));
printf("Result: %s\n", processed); // "HELLO WORLD"
char *text2 = "hello";
char *result = replace(upper(text2), "HELLO", "GOODBYE");
printf("Result: %s\n", result); // "GOODBYE"
return 0;
}
```
## Socket Programming
RC provides native socket functions for network programming.
### Basic HTTP Server
```c
int main() {
int sockfd;
int client_fd;
char buffer[1024];
sockfd = socket(AF_INET(), SOCK_STREAM(), 0);
bind(sockfd, 8080);
listen(sockfd, 10);
printf("Server listening on port 8080\n");
client_fd = accept(sockfd, 0, 0);
printf("Client connected\n");
recv(client_fd, buffer, 1024, 0);
send(client_fd, "HTTP/1.1 200 OK\n\nHello!\n", 24, 0);
close(client_fd);
close(sockfd);
return 0;
}
```
### Socket Functions
**socket(domain, type, protocol)** - Create socket
```c
int sockfd = socket(AF_INET(), SOCK_STREAM(), 0);
```
**bind(sockfd, port)** - Bind socket to port
```c
bind(sockfd, 8080);
```
**listen(sockfd, backlog)** - Listen for connections
```c
listen(sockfd, 10);
```
**accept(sockfd, addr, addrlen)** - Accept connection
```c
int client = accept(sockfd, 0, 0);
```
**recv(sockfd, buffer, length, flags)** - Receive data
```c
int bytes = recv(client, buffer, 1024, 0);
```
**send(sockfd, data, length, flags)** - Send data
```c
send(client, "Hello", 5, 0);
```
**close(fd)** - Close socket
```c
close(sockfd);
```
**Constants:**
- `AF_INET()` - IPv4 address family
- `SOCK_STREAM()` - TCP socket type
## Comments
RC supports single-line comments using `//`.
```c
int main() {
// This is a comment
int x = 10; // Inline comment
// Multiple lines of comments
// can be written like this
printf("Hello\n");
return 0;
}
```
---
## Complete Examples
### Example 1: Text Processing
```c
int main() {
char *text = " hello WORLD ";
char *cleaned = strip(text);
char *lowercase = lower(cleaned);
char *replaced = replace(lowercase, "world", "rc");
char *final = upper(replaced);
printf("Original: '%s'\n", text);
printf("Final: '%s'\n", final);
return 0;
}
```
### Example 2: String Analysis
```c
int main() {
char *email = "user@example.com";
int at_pos = strpos(email, "@");
int dot_pos = strpos(email, ".");
if (at_pos > 0 && dot_pos > at_pos) {
printf("Valid email format\n");
char *username = substr(email, 0, at_pos);
printf("Username: %s\n", username);
}
return 0;
}
```
### Example 3: Loop with Conditions
```c
int main() {
int i = 0;
while (i < 10) {
if (i == 5) {
printf("Halfway!\n");
}
printf("Count: %d\n", i);
i = i + 1;
}
printf("Done!\n");
return 0;
}
```
### Example 4: Recursive Fibonacci
```c
int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int i = 0;
while (i < 10) {
printf("fib(%d) = %d\n", i, fibonacci(i));
i = i + 1;
}
return 0;
}
```
---
## Best Practices
1. **Always initialize variables** before use
2. **Use meaningful variable names** for readability
3. **Check string operation results** for edge cases
4. **Close sockets** after use in network programming
5. **Return 0** from main to indicate success
6. **Use comments** to explain complex logic
7. **Test edge cases** like empty strings and zero values
8. **Validate user input** in interactive programs
## Limitations
- No floating-point arithmetic (use integers)
- No structs, unions, or custom types
- No preprocessor directives
- Only `\n` escape sequence supported
- Limited to basic C subset
- No file I/O (except socket I/O)
- Memory is managed automatically
---
For more examples, see the `tests/` and `examples/` directories in the RC repository.