C++ Crash Course: a fast-Paced Introduction


The Structure of a Basic C++ Program



Yüklə 7 Mb.
Pdf görüntüsü
səhifə39/71
tarix20.09.2023
ölçüsü7 Mb.
#145939
1   ...   35   36   37   38   39   40   41   42   ...   71
C Crash Course A Fast-Paced Introduction by Josh Lospinoso

The Structure of a Basic C++ Program
In this section, you’ll write a simple C++ program and then compile and 
run it. You write C++ source code into human-readable text files called 
source files. Then you use a compiler to convert your C++ into executable 
machine code, which is a program that computers can run. 
Let’s dive in and create your first C++ source file.
Creating Your First C++ Source File 
Open your favorite text editor. If you don’t have a favorite just yet, try Vim, 
Emacs, or gedit on Linux; TextEdit on Mac; or Notepad on Windows. Enter 
the code in Listing 1-1 and save the resulting file to your desktop as main.cpp.
#include  
u
int main
v
(){
printf("Hello, world!"); 
w
return 0; 
x
}
Hello, world! 
w
Listing 1-1: Your first C++ program prints 
Hello, world!
 to the screen.
The Listing 1-1 source file compiles to a program that prints the char-
acters 
Hello, world!
to the screen. By convention, C++ source files have a .cpp 
extension.
N O T E
 
In this book, listings will include any program output immediately after the program’s 
source; the output will appear in gray. Numerical annotations will correspond with 
the line that produced the output. The 
printf
 statement in Listing 1-1, for example,
is responsible for the output 
Hello, world!
, so these share the same annotation 
w
.
Main: A C++ Program’s Starting Point
As shown in Listing 1-1, C++ programs have a single entry point called the 
main
function 
v
. An entry point is a function that executes when a user runs 
a program. Functions are blocks of code that can take inputs, execute some 
instructions, and return results.
Within 
main
, you call the function 
printf
, which prints the characters 
Hello, world!
to the console 
w
. Then the program exits by returning the 
exit code 
0
to the operating system 
x
Exit codes are integer values that the 
operating system uses to determine how well a program ran. Generally, a 


Up and Running
5
zero (
0
) exit code means the program ran successfully. Other exit codes 
might indicate a problem. Having a return statement in 
main
is optional; the 
exit code defaults to 
0
.
The 
printf
function is not defined in the program; it’s in the 
cstdio
library 
u
.

Yüklə 7 Mb.

Dostları ilə paylaş:
1   ...   35   36   37   38   39   40   41   42   ...   71




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin