リリース・改善中
C++ ガイド · 2/6
この章は現在、英語でのみ提供しています。
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.
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
}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 intAn uninitialized local variable holds an indeterminate value, and reading it is a bug. Give every variable an initial value when you declare it.
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.
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"The compiler picks an overload by matching the argument types at the call site. If two candidates are equally good, the call is ambiguous and won't compile.
if, switch, while and the classic for loop look much like they do in C. Since C++11 there is also the range-based for, which visits every element of a container, and since C++17 if can declare a variable right in its header.
#include <iostream>
#include <vector>
int main() {
std::vector<int> scores{90, 72, 85, 60};
for (int s : scores) { // each element by value
std::cout << s << ' ';
}
for (auto& s : scores) { // by reference, so we can modify
s += 5;
}
for (const auto& s : scores) { // read-only access
if (s >= 90) std::cout << "A ";
else if (s >= 80) std::cout << "B ";
else std::cout << "C ";
}
if (auto n = scores.size(); n > 3) { // C++17 if with initializer
std::cout << "\n" << n << " scores\n";
}
int i = 0;
while (i < 3) { ++i; }
}std::cout works with every standard version. C++20 added std::format in <format>, which builds a string from a format string with {} placeholders, and C++23 added std::print in <print> to write formatted output directly. Standard library implementations shipped these at different times, so an older toolchain may not have them yet.
#include <format>
#include <iostream>
#include <string>
int main() {
std::string name{"Lee"};
int score = 92;
std::cout << std::format("{} scored {} points.\n", name, score);
std::cout << std::format("{:>8.2f}|\n", 3.14159); // width 8, 2 decimals
}If std::format isn't available to you, keep using std::cout, or use the open-source {fmt} library, which the standard facility was based on.
main, and statements end with ;.auto for type deduction, and const or constexpr for values that never change.const reference when you only read.for to walk containers, and std::format for formatted text when your toolchain supports it.
コメント 0件
ログイン · ログインするとコメントできます。
最初のコメントを書いてみましょう。