C Language – 02 Hello World!

In the previous article on computer programming languages, we introduced the definition and development stages of programming languages. Now, we will specifically write executable code for a computer programming language and create our first program, Hello World.

The process of inputting, modifying, and saving source code using a text editor (such as Dev++, VS Code, etc.) is called program editing.

C Language

// Include the standard input-output library header file to allow the program to use standard input-output functions like `printf`.
#include <stdio.h>
// Define the entry point of the program, the `main` function, with a return type of `int`.
int main(){
 // Call the `printf` function to output the string `Hello World!` and move to the next line.
 printf("Hello World!\n");
 // Return 0, indicating that the program exited normally.
 return 0;
}

“Programs written in high-level languages (such as C, Java, Python, etc.) are called source programs”, which are the original code written by programmers, highly readable but not directly executable by computers.

#include <stdio.h>
  • This is a preprocessor directive, used to include the standard input-output library (<span>stdio.h</span>).
  • <span>#include</span> is a directive for the C language preprocessor, used to insert the contents of the specified “header file” (here, <span>stdio.h</span>) into the current file.
  • <span>stdio.h</span> is the header file for the standard input-output library, which contains function declarations and macro definitions for input and output operations. For example, the declaration of the <span>printf</span> function is in this header file. If this header file is not included, the compiler will not recognize the <span>printf</span> function.
int main(){}
  • This is the entry point of the program, defining a function named <span>main</span>.
  • <span>int</span> is the return type of the function, indicating that the <span>main</span> function will return an integer value (<span>int</span>).
  • <span>main</span> is the entry function of a C program, where the execution of the program begins.
  • The function body is enclosed in a pair of curly braces <span>{}</span>, which contains the code to be executed by the function.
printf("Hello World!\n");
  • This is a call to the <span>printf</span> function, used to print the string to standard output (usually the terminal or console).
  • <span>printf</span> is a function in the C standard library used for formatted output. Print: to print, output function: function
  • <span>"Hello World!\n"</span> is the string to be output, where:
    • <span>"Hello World!"</span> is the text to be printed.
    • <span>\n</span> is the newline character, indicating that after printing the string, it should move to the next line.
  • <span>printf</span> will output the string in parentheses to the standard output device (usually the screen) and return the number of characters output.
return 0;
  • This is the return statement of the <span>main</span> function.
  • <span>return</span> is a keyword in C used to return a value from a function.
  • <span>0</span> is the returned value, usually indicating that the program executed successfully. In C, returning <span>0</span> when the program ends normally is a common convention.
  • When the <span>main</span> function reaches <span>return 0;</span>, the program will end and return <span>0</span> as the exit status code to the operating system.

Header Files

Header files are a special type of file in C (and many other programming languages), usually with a <span>.h</span> extension. They are mainly used to store declarations that need to be shared in the program (such as function declarations, variable declarations, macro definitions, type definitions, etc.).“The main purpose of header files is to provide interface information for the program, making the code more modular, easier to maintain, and reusable.“In C, a source file can include” zero or more header files.

Main Content of Header Files

  1. Function Declarations Declare the name, parameter types, and return type of a function, but do not include the implementation of the function. For example:

    int add(int a, int b);
    

    This tells the compiler that there is a function named <span>add</span> that takes two integer parameters and returns an integer.

  2. Variable Declarations Declare global or external variables. For example:

    extern int globalVar;
    

    This tells the compiler that there is a global variable named <span>globalVar</span> defined elsewhere.

  3. Macro Definitions Define constants or simple code snippets. For example:

    #define PI 3.14159
    

    This defines a constant named <span>PI</span> with a value of <span>3.14159</span>.

  4. Type Definitions Define new data types. For example:

    typedef struct{
     int x;
     int y;
     }Point;
    

    This defines a structure type named <span>Point</span>.

Functions of Header Files

  1. Code Reuse Header files can be included in multiple source files, allowing function declarations, variable declarations, and other information to be shared in multiple places, avoiding duplication.

  2. Modularity Separating interfaces (declarations) from implementations (definitions) makes the code clearer and easier to maintain. Header files are responsible for declaring interfaces, while implementations are placed in source files (<span>.c</span> files).

  3. Improving Compilation Efficiency By separating declarations and definitions, the compiler only needs to parse the declarations in the header files, rather than parsing the complete implementation code each time, thus improving compilation efficiency.

  4. Hiding Implementation Details Header files only expose necessary interface information, hiding specific implementation details, so that users of the library do not need to care about the internal implementation.

Examples of Header Files

In C, a source file can exist without a header file. Here is a detailed explanation of this situation:

Why Can There Be No Header Files

Header files are mainly used to declare functions, define macros, declare global variables, and define data structures. They are a convenient way to reuse code and achieve modularity, but it is not mandatory to use them. A source file (usually a <span>.c</span> file) is the basic unit of a C program, containing the main body of the code. Even without header files, a source file can still contain complete function definitions and variable declarations, as long as these contents meet the logical requirements of the program, the source file can compile and run normally.

“Simple Program Example”: For some very simple programs, such as those containing only a <span>main</span> function, it is entirely possible to not use header files. For example:

int main(){
 printf("Hello, World!\n");
 return 0;
}

This program, although it does not explicitly include header files, will actually have the compiler automatically include some standard header files (such as <span>stdio.h</span>) during compilation, allowing the <span>printf</span> function to be correctly recognized and used. Therefore, from the user’s perspective, this source file does not explicitly include header files, but it can still run normally.

Possible Issues Encountered

  1. “Missing Function Declarations”: If the source file calls other functions that are not declared in the header files, the compiler may report an error, indicating that the function is undefined or implicitly declared.
  2. “Missing Global Variables and Macro Definitions”: If the program relies on global variables or macro definitions that are not defined in the header files, it may lead to the program failing to compile or run normally.
  3. “Code Readability and Maintainability Issues”: Not having header files can make the structure of the code unclear, which is not conducive to modular development and code reuse. For complex projects, using header files can better organize the code and improve readability and maintainability.

Although C source files can exist without header files, in actual development, header files are very useful tools that can help organize code, improve code readability and maintainability. For complex projects, it is recommended to use header files reasonably to declare functions, define macros, and global variables, etc.

Custom Header Files

Suppose we have a simple math library that includes an addition function <span>add</span> and a subtraction function <span>subtract</span>. We can place their declarations in a header file:

//math.h
// Function declarations
int add(int a, int b);
int subtract(int a, int b);

Then implement these functions in the source file:

//math.c
#include "math.h"

int add(int a, int b){
 return a + b;
}
int subtract(int a, int b){
 return a - b;
}

In other source files that need to use these functions, simply include the header file <span>math.h</span> to call these functions:

//main.c
#include "math.h"
#include <stdio.h>

int main(){
 int sum = add(3, 4);
 int diff = subtract(10, 5);
 printf("Sum: %d\n", sum);
 printf("Difference: %d\n", diff);
 return 0;
}

Standard Library Header Files

The C standard library also includes many header files, such as:

  • <span>stdio.h</span>: for standard input-output functions.
  • <span>stdlib.h</span>: for standard library functions, such as memory allocation, random number generation, etc.
  • <span>string.h</span>: for string operations.
  • <span>math.h</span>: for mathematical functions.

Main Function

In C, the “main function” is the only entry point of the program, which is the function executed first when the program runs.

Characteristics and Basic Syntax

  1. “Uniqueness”: A program can only have one <span>main</span> function.
  2. “Standard Compliance”: Must follow <span>int main(void)</span> or <span>int main(int, char*[])</span> to ensure portability.
  3. “System Dependency”: The specific meaning of the return value may vary by operating system (but 0 usually indicates success).

If the main function is defined incorrectly (such as a non-<span>int</span> return value), the compiler will report an error or warning, and the program may not run correctly.

The standard definition forms of the main function are two (supported by C99 and above)

int main(void){
// Code logic
 return 0; // Return status code (0 usually indicates success)
}
int main(){
// Code logic
 return 0; // Return status code (0 usually indicates success)
}

Or with command line parameters:

int main(int argc, char* argv[]){
 //argc: number of parameters
 //argv: array of parameter strings
 return 0;
}
  • “Return Value Type”:
    • Must be <span>int</span> (indicating the program exit status code).
    • <span>return 0;</span> indicates success, while a non-zero value (such as <span>1</span>) indicates an error (captured by the operating system or caller).
  • “Parameters”:
    • If there are no parameters, <span>void</span> must be explicitly written (empty parameters), otherwise, in C, any parameters may be allowed (not recommended).
    • When there are parameters, <span>argc</span> and <span>argv</span> receive the number of command line parameters and the specific parameters (<span>argv[0]</span> is the program name).
  • “Omitting <span>return</span>:
    • Since C99, if <span>return 0;</span> is not written, the compiler will automatically return 0 implicitly (only for the <span>main</span> function).

Common non-standard forms (not recommended)

  • <span>void main()</span>:

    Some old compilers allow this (like TurboC), but it does not comply with C standards and has poor portability. Modern compilers will warn. (Outdated)

    void main(){
     // Code logic
     return 0; // Return status code (0 usually indicates success)
    }
    
  • “No Return Value”: Omitting the return value may lead to undefined behavior.

    int main(){
     // Code logic
    }
    

Examples

“No Parameter Version”

#include <stdio.h>

int main(){
 printf("Hello, World!\n");
 return 0;
}

“Command Line Parameter Version”

#include <stdio.h>

int main(int argc, char *argv[]) {
 printf("Program Name: %s\n", argv[0]);
 printf("Number of Parameters: %d\n", argc - 1);
 for (int i = 1; i < argc; i++) {
 printf("Parameter %d: %s\n", i, argv[i]);
 }
 return 0;
}

Running Example:

E:\a-MyCode\c-CppCode\250328CZeroStudy\p0002>p0002.exe foobar
Program Name: p0002.exe
Number of Parameters: 2
Parameter 1: foo
Parameter 2: bar

Comments

C language supports two types of comments, with specific rules and examples as follows:

Single Line Comments (<span>//</span>)

  • “Syntax”: Starts with <span>//</span> and ends at the end of the line.

  • “Characteristics”:

    • Only comments on the content of the current line.
    • Can be placed on the right side of the code or occupy an independent line.
    • “Cannot span lines”: If multiple lines need to be commented, <span>//</span> must be repeated.
  • “Example”:

    int x = 10; // This is a single line comment explaining the assignment of variable x
    // This is another independent single line comment
    

Block Comments (<span>/* */</span>)

  • “Syntax”: Starts with <span>/*</span> and ends with <span>*/</span>.
  • “Characteristics”:
    • Can span multiple lines or comment on a part of a code block.
    • “Must appear in pairs”: If missing <span>*/</span>, it will cause a compilation error (subsequent code will be misinterpreted as comments).
  • “Example”:
    /* This is a multi-line comment
    It can span multiple lines,
    Suitable for detailed explanations of code logic */
    
    int y = /* Inline comment */ 20; // Comment inserted in the middle of code
    

Notes

  1. “Nesting Issues”:

  • Block comments “cannot be nested”. For example, the following code will report an error:
    /* Outer comment /* Inner comment */ // Error! Nesting causes the outer comment to end prematurely
    
  • However, single line comments can appear within block comments:
    /* This is a block comment
    // Contains a single line comment
    Still part of the block comment */
    
  • “Code Debugging”:

    • Block comments can be used to temporarily disable blocks of code (for debugging):
      /* printf("Do not execute this code"); */
      
  • “Style Suggestions”:

    • “Single Line Comments”: Used for brief explanations or end-of-line comments.
    • “Block Comments”: Used for multi-line explanations or documentation of complex logic.

    Program Execution

    “The machine language code file generated by the compiler from the source program is called the target program”, usually in binary form, recognizable by the computer but poorly readable.

    “The process of converting source program code into a target program is called program compilation, completed by the compiler”. The compiler checks for syntax errors and converts high-level language code into machine language code.

    “The final program generated after linking the target program can be run directly in the operating system, called an executable program”, usually an independent file (like a .exe file).

    “The process of merging the target program with the required library files to generate an executable program is called program linking”. The linker resolves function and variable references in the program.

    C Language - 02 Hello World!

    Ref: C Programming (5th Edition) by Tan Haokang

    Leave a Comment