U E D R , A S I H C RSS

AcceleratedC++/Chapter2

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

----
어째서 C의 프는0부터? 인지... 간단한 대답이 나와 있더군요. - 톱아보다

----
AcceleratedC++
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:22:25
Processing time 0.0132 sec