This chapter covers the building blocks you will use in every C++ program: the main function, variables and auto, references, functions and overloading, control flow, and printing output.
main and statements
Every C++ program starts in main. Statements end with a semicolon, blocks are wrapped in braces, and comments come in two flavors: // for a single line and /* ... */ for a span.
#include <iostream>
int main(int argc, char* argv[]) {
// argc: number of arguments, argv: the arguments as C strings
std::cout << argc << " argument(s), program: " << argv[0] << '\n';
return 0; // optional in main: falling off the end returns 0
}
Variables and auto
A variable is declared with a type and a name. Brace initialization ({}) is worth making a habit, because the compiler rejects narrowing conversions that would silently lose data. auto deduces the type from the initializer, and const makes a value read-only.
#include <string>
int count{10};
double ratio = 0.75;
const int max_users{100}; // cannot be modified
constexpr int buffer = 256; // value known at compile time
auto name = std::string{"Kim"}; // std::string
auto total = count * 2; // int
// int bad{3.14}; // error: narrowing from double to int
An uninitialized local variable holds an indeterminate value, and reading it is a bug. Give every variable an initial value when you declare it.
References
A reference (&) is an alias for an existing object. References are the usual way to pass large objects to functions without copying them. If the function only reads the argument, take it by const reference.
#include <string>
void add_suffix(std::string& text) { // modifies the caller's string
text += "!";
}
std::size_t length_of(const std::string& text) { // read-only, no copy
return text.size();
}
int main() {
std::string greeting{"hello"};
add_suffix(greeting); // greeting is now "hello!"
auto n = length_of(greeting); // 6
int value = 1;
int& alias = value;
alias = 5; // value is 5 too
}
A reference must be bound when it is declared and can never be reseated to refer to something else. When you need something that can change targets or be empty, use a pointer.
Functions and overloading
A function has a return type, a name and a parameter list. Several functions can share a name as long as their parameter lists differ; this is called overloading. Parameters can also have default values.
#include <string>
int area(int w, int h) { return w * h; }
double area(double radius) { return 3.14159 * radius * radius; }
std::string repeat(const std::string& s, int times = 2) {
std::string out;
for (int i = 0; i < times; ++i) out += s;
return out;
}
// area(3, 4) -> 12
// area(1.5) -> area of a circle
// repeat("ab") -> "abab", repeat("ab", 3) -> "ababab"
0 則留言
登入 · 登入後即可留言。