Chapter 2 ¶
μ€μ μμ€ ¶
~cpp #include <iostream> #include <string> // say what standard-library names we use using std::cin; using std::cout; using std::string; using std::endl; int main() { // ask for person's name cout << "Please enter your first name: "; // read the name string name; cin >> name; // build the message that we intend to write const string greeting = "Hello, " + name + "!"; // the number of blacks surrounding the greeting const int pad = 1; // the number of rows and columns to write const int rows = pad * 2 + 3; const string::size_type cols = greeting.size() + pad * 2 + 2; // write blank line to separate the output from the input cout << endl; // write rows // invariant: we have written r rows so far for (int r = 0; r != rows ; ++r) { string::size_type c = 0; // invariant: we have written c while (c != cols) { // is it time to write the greeting? if (r == pad + 1 && c == pad + 1) { cout << greeting; c += greeting.size(); } else { // are we on the border? if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) cout << "*"; else cout << " "; ++c; } } cout << endl; } return 0; }
----
μ§λ¬Έ ¶
μ±
μ 보면 (21νμ΄μ§),
----
~cpp // invariant : we have written r rows so far int r = 0; // setting r to 0 makes the invariant true while( r != rows ) { // we can assume that the invariant is true here // writing a row of output makes the invariant false std::cout << std::endl; // incrementing r makes the invariant true again ++r; } // we can conclude that the invariant is true hereμ½λμ λ§μ§λ§ λΆλΆμμ invariant κ° λ€μ true λ‘ λλκ²μΌκΉμ.? invariant κ° λ¬΄μμΈμ§ μμ§ κ°λ μ΄ μ‘νμ§ μμμ. -_-a - μμΈν
μ λ μ΄μ μμΌ AcceleratedC++μ λ³΄κ³ μλλ°μ. loop invariantλ rλ² μννλ€λΌλ κ²μ λ§νμ§ μμκΉμ?
rμ΄ μ²μμ 0μ΄λκΉ whileμ μ§μ νλ μμ μλ coutμ 0λ² μννμν κ³ λ°λΌμ r = 0, μννμ = 0 λ°λΌμ λΆλ³μμ μ°Έ
rμ΄ 0μ΄κ³ coutμ νλ² μννλ©΄ r = 0, μννμ = 1 λ°λΌμ λΆλ³μ κ±°μ§
whileμ λ§μ§λ§ μ μ rμ 1 μ¦κ°μν€λ―λ‘... r = 1, μννμ = 1 λ°λΌμ λΆλ³μ μ°Έ
λ°λΌμ whileμ 쑰건μ λΉκ΅μμλ r = 1, μννμ =1 λ°λΌμ λΆλ³μ μ°Έ...
λ cout μ μννκ² λλ€λ©΄ r = 1, μννμ = 2λκΉ λΆλ³μ κ±°μ§...
μμ μ http://www.pragmaticprogrammer.com/ppllc/papers/1998_05.html μμ invariantsλΌλ λ§μ΄ λμμλλ° κ°μ κ°λ μΌλ‘ μκ°νλ©΄ λ λ €λ γ ‘,.γ ‘; --Benghun
rμ΄ μ²μμ 0μ΄λκΉ whileμ μ§μ νλ μμ μλ coutμ 0λ² μννμν κ³ λ°λΌμ r = 0, μννμ = 0 λ°λΌμ λΆλ³μμ μ°Έ
rμ΄ 0μ΄κ³ coutμ νλ² μννλ©΄ r = 0, μννμ = 1 λ°λΌμ λΆλ³μ κ±°μ§
whileμ λ§μ§λ§ μ μ rμ 1 μ¦κ°μν€λ―λ‘... r = 1, μννμ = 1 λ°λΌμ λΆλ³μ μ°Έ
λ°λΌμ whileμ 쑰건μ λΉκ΅μμλ r = 1, μννμ =1 λ°λΌμ λΆλ³μ μ°Έ...
λ cout μ μννκ² λλ€λ©΄ r = 1, μννμ = 2λκΉ λΆλ³μ κ±°μ§...
μμ μ http://www.pragmaticprogrammer.com/ppllc/papers/1998_05.html μμ invariantsλΌλ λ§μ΄ λμμλλ° κ°μ κ°λ μΌλ‘ μκ°νλ©΄ λ λ €λ γ ‘,.γ ‘; --Benghun
μ΄μ§Έμ Cμ 루νλ0λΆν°? μΈμ§... κ°λ¨ν λλ΅μ΄ λμ μλκ΅°μ. - ν±μ보λ€
AcceleratedC++