Hello World
Let’s take a look at the actual code that gets executed when using c3c run. Open src/main.c3 and you should find a simple hello world program. We will break down the contents of this program step by step so that you can easily follow and understand the code.
Modules
module hello_world;
import std::io;The first line declares the main.c3 file as a module named hello_world. Modules neatly group functions, variables, macros and more into a namespace. This allows you to better organize your code and avoid naming conflicts. You can also have modules inside of other modules, these are appropriately called submodules.
To access the functions, variables and macros inside of your hello_world module from another module you can use the import keyword followed by the name of the module you want to import. This can be seen in action on the second line, where the io submodule of the standard library (std) is imported.
The Entry Point
Let’s take a closer look at the main function. Its purpose is to provide an entry point to your program, meaning that’s where the programs execution begins. Since a program can only have one entry point, there can only be one main function.
fn int main(String[] args)
{
}Like every function in C3 the main function starts with the fn keyword followed by it’s return type, int. After the function’s name, main, come the arguments inside parentheses (). It is good style in C3 to dedicate a line to each curly bracket {}.
Note
We will revisit the String[] args argument later to explain its usage.
Printing to the console
Inside of the main function, we can find the following lines:
io::printn("Hello, World!");
return 0;The first line prints "Hello, World!" followed by a newline character to the console. It uses the printn macro from the io submodule, which we imported from std. In C3, instead of writing std::io::printn as you would in C++, the convention is to use path-shortening. Path-shortening allows you to only use the lowest submodule, in this case io, which helps keeping your code clean.
The second line uses the return keyword to, who guessed it, return a value. In this case it returns the number 0. Removing this line would result in a compilation error, as the main function requires an integer to be returned (remember the int return type?).
Note
The number 0 indicates that the program ran successfully, whilst other numbers (like 1) can indicate errors or different exit statuses. You may have noticed this using c3c run, when the compiler reports the following line: Program completed with exit code 0.
Most lines in C3 end with a semicolon ; as can be seen with the two lines above.
Congratulations, you now know what a basic “Hello World” program looks like in C3.