Main & CLAs#
Main#
Definition
The main function is crucial because it is the starting point of a C++ program. It allows you to define the program’s logic and perform various operations based on your requirements. It also provides an entry point for the program to interact with the operating system and handle command-line arguments, if necessary. Without a main function, the program cannot be executed as a standalone program.
Use Cases
- CLAs
Working with Command-line Arguments
allows for variables to be left defined at runtime
- Executables
Executing compiled code
Pros & Cons
Code organization
Provides a clear structure for where execution begins
Control flow
Allows you to manage program flow efficiently
Reusability
Promotes reusable code
Complexity
In some languages, a main function may introduce unnecessary complexity
Limited flexibility
In some cases, it might not be suitable for specific program types
main
Syntax#
pseudocode for main function:
begin
// Your program logic here
end
1#include <iostream>
2int main() {
3 std::cout << "Hello, World!" << std::endl;
4 return 0;
5}
1def main():
2 print("Hello, World!")
3
4if __name__ == "__main__":
5 main()
1// Java Main Function Example
2public class MainExample {
3 public static void main(String[] args) {
4 System.out.println("Hello, World!");
5 }
6}
1// Rust Main Function Example
2fn main() {
3 println!("Hello, World!");
4}
<iframesrc=“https://www.youtube.com/embed/380D9mmWXl8?si=5RyMKgeytpo9QRv7” title=“YouTube video player” frameborder=“0” allow=“accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share” allowfullscreen>
1// Go Main Function Example
2package main
3
4import "fmt"
5
6func main() {
7 fmt.Println("Hello, World!")
8}
Output
In each
main
function, the objective is to define the entry point for the program And print the common ‘simple program’ example of “Hello, World!” to the terminal
Hello, World!
Command-line Arguments#
Definition
argc
argument count : keeps track of the total number of arguments passed at runtime
argv
argument vector : avector
collection of arguments passed and accessible at runtime
Use Cases
Accepting user input from the command line
Configuring program behavior using command-line options
Pros & Cons
Flexibility
Users can customize program behavior without changing the code
Automation
Batch processing and scripting become possible
Standardization
A common way to interact with command-line programs
Complexity
Handling command-line arguments can become complex for advanced use cases
Error-prone
Incorrect input can lead to unexpected behavior
argc
& argv
Syntax#
pseudocode for handling argc and argv:
begin
// Parse command-line arguments
if argc > 1:
for i from 1 to argc-1:
if argv[i] is a valid option:
// Handle the option
else:
// Handle other arguments
else:
// No arguments provided
end
1#include <iostream>
2
3int main(int argc, char* argv[]) {
4 if (argc > 1) {
5 for (int i = 1; i < argc; ++i) {
6 if (strcmp(argv[i], "--help") == 0) {
7 std::cout << "Help information" << std::endl;
8 } else {
9 std::cout << "Argument: " << argv[i] << std::endl;
10 }
11 }
12 } else {
13 std::cout << "No arguments provided." << std::endl;
14 }
15 return 0;
16}
1import sys
2
3def main():
4 if len(sys.argv) > 1:
5 for arg in sys.argv[1:]:
6 if arg == "--help":
7 print("Help information")
8 else:
9 print(f"Argument: {arg}")
10 else:
11 print("No arguments provided.")
12
13if __name__ == "__main__":
14 main()
1public class CommandLineArgsExample {
2 public static void main(String[] args) {
3 if (args.length > 0) {
4 for (String arg : args) {
5 if (arg.equals("--help")) {
6 System.out.println("Help information");
7 } else {
8 System.out.println("Argument: " + arg);
9 }
10 }
11 } else {
12 System.out.println("No arguments provided.");
13 }
14 }
15}
1use std::env;
2
3fn main() -> Result<(), std::env::ArgsError> {
4 let args: Vec<String> = env::args().collect();
5
6 if args.len() > 1 {
7 for arg in &args[1..] {
8 if arg == "--help" {
9 println!("Help information");
10 } else {
11 println!("Argument: {}", arg);
12 }
13 }
14 } else {
15 println!("No arguments provided.");
16 }
17
18 Ok(())
19}
1package main
2
3import (
4 "fmt"
5 "os"
6)
7
8func main() {
9 args := os.Args[1:] // Exclude the program name
10
11 if len(args) > 0 {
12 for _, arg := range args {
13 if arg == "--help" {
14 fmt.Println("Help information")
15 } else {
16 fmt.Println("Argument:", arg)
17 }
18 }
19 } else {
20 fmt.Println("No arguments provided.")
21 }
22}
Output
We prompt the user to enter their exam score and compare it with the
passing_threshold
value of60
. If theexam_score
is greater than or equal to60
, the program outputs a success message indicating that the student passed the exam. Otherwise, it prints a message stating that the student did not pass and should try again.Assume the user enters
75
as input for all the examples.Since the input
75
is greater than the passing threshold of60
, the output is: `Congratulations! You passed the exam.``.
These respective runtime commands each receive the following output…
// cpp
./a.out arg1 arg2
// python
python script.py arg1 arg2
// java
java CommandLineArgsExample arg1 arg2
// rust
./target/debug/myapp arg1 arg2
// golang
go run script.go arg1 arg2
Argument: arg1
Argument: arg2