<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Random Notes</title>
	<atom:link href="http://www.aleksey.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.aleksey.com</link>
	<description>Just another WordPress weblog</description>
	<lastBuildDate>Thu, 21 Apr 2011 03:41:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.5</generator>
		<item>
		<title>Lesson 10 &#8211; Drawing on The Console</title>
		<link>http://www.aleksey.com/2011/04/20/lesson-10-drawing-on-the-console/</link>
		<comments>http://www.aleksey.com/2011/04/20/lesson-10-drawing-on-the-console/#comments</comments>
		<pubDate>Wed, 20 Apr 2011 20:07:26 +0000</pubDate>
		<dc:creator>Aleksey Sanin</dc:creator>
				<category><![CDATA[Practical Programming]]></category>

		<guid isPermaLink="false">http://www.aleksey.com/?p=202</guid>
		<description><![CDATA[Believe it or not, I can actually draw. Jean-Michel Basquiat Practical Programming As we learned in previous lessons, programmers often build libraries of functions to provide a “customized” version of C/C++ language. Today, we are going to build our own &#8230; <a href="http://www.aleksey.com/2011/04/20/lesson-10-drawing-on-the-console/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em>Believe it or not, I can actually draw.</em><br />
<a href="https://secure.wikimedia.org/wikipedia/en/wiki/Jean-Michel_Basquiat"><em>Jean-Michel Basquiat</em></a></p>
<p><a href="../2011/03/17/practical-programming/">Practical Programming</a></p>
<p>As we learned in previous lessons, programmers often build libraries of functions to provide a “customized” version of C/C++ language. Today, we are going to build our own library of functions to draw things on the console. Drawing on the console is not a part of C/C++ standard and the underlying functions we will be using are specific to the Microsoft Windows API. The Linux, Mac OSX or other operating systems will require a different implementation.</p>
<p>Microsoft Windows API is very well documented through <a href="http://msdn.microsoft.com">Microsoft Developer Network </a>(MSDN). We are going to look at the <a href="http://msdn.microsoft.com/en-us/library/ms682010%28v=VS.85%29.aspx">Consoles section</a> and the <a href="http://msdn.microsoft.com/en-us/library/ms682073%28v=VS.85%29.aspx">Console Functions</a>. But before we jump into the implementation, lets define what the console is and what functions do we want to implement.</p>
<p>A console is a two dimensional rectangular screen with (0,0) point in the top left corner. X-axis goes from left to right and Y axis goes from top to bottom. A console has a size &#8211; the rectangular width and height. Only the points inside this rectangular are visible to the user. A console also has a notion of “cursor” &#8211; a point on the console where we can print a character. When we print a character, the cursor moves one position to the right. If we hit the console’s right border, then cursor moves to the first position on the next’s line. To draw on the console, we would need to implement the following functions:</p>
<pre style="padding-left: 30px;">SIZE ConsoleGetSize();       // gets the size of the console
COORD ConsoleGetCursor();    // gets the current position of the cursor
void ConsoleSetCursor(COORD p); // moves cursor to point p
void ConsolePrint(char ch);  // prints a character at the current cursor’s position
void ConsoleClear();         // clears the console</pre>
<p>To implement the first two functions, we will need to use <a href="http://msdn.microsoft.com/en-us/library/ms683171%28v=VS.85%29.aspx">GetConsoleScreenBufferInfo() function</a>. This function queries the Windows console object and returns back information about the console in the <a href="http://msdn.microsoft.com/en-us/library/ms682093%28v=VS.85%29.aspx">CONSOLE_SCREEN_BUFFER_INFO structure</a>:</p>
<ul>
<li>the current console size is returned in the <em>dwSize</em> field;</li>
<li>the current cursor position is returned in the <em>dwCursorPosition</em> field.</li>
</ul>
<p>We will also need to use <a href="http://msdn.microsoft.com/en-us/library/ms683231%28v=VS.85%29.aspx">GetStdHandle() function</a> to retrieve the “handle” of the current console. An application may use multiple consoles to improve performance and make rendering smoother. For now, let’s simply use the main console. Finally, don’t forget to include &lt;<em>windows.h</em>&gt; file that contains definition for the Windows API functions we are going to use!</p>
<pre style="padding-left: 30px;">// returns a console size or invalid size {-1,-1} on error
SIZE ConsoleGetSize() {
    HANDLE hConsole;
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    SIZE szError = {-1, -1}; // special return value to indicate error

    // get special console handle to identify the console
    hConsole = GetStdHandle( STD_OUTPUT_HANDLE );
    if(hConsole == INVALID_HANDLE_VALUE) {
        return szError; // the invalid size value to indicate error
    }

    // get information about console
    if (GetConsoleScreenBufferInfo(hConsole, &amp;csbi) == 0) {
       return szError; // the invalid size value to indicate error
    }

    // done
    return csbi.dwSize;
}</pre>
<p>Can you write a similar function <em>ConsoleGetCursor</em>() that returns <em>dwCursorPosition</em> field instead of the <em>dwSize</em> field?</p>
<p>To implement the <em>ConsoleSetCursor</em>() function we will need to use  <a href="http://msdn.microsoft.com/en-us/library/ms686025%28v=VS.85%29.aspx">SetConsoleCursorPosition() function</a> from Microsoft Windows API. Again, we will need first to get the console’s handle (this is the first parameter for the <em>SetConsoleCursorPosition</em>() function). The rest should be easy! Can you write <em>ConsoleSetCursor</em>() yourself?</p>
<p>Finally, you already know how to implement <em>ConsolePrint</em>() and <em>ConsoleClear</em>() functions: use the standard “cout” to print a character on the console and use the <em>system(“cls”) </em>call to clear the console!</p>
<p>Now we have all the console functions to draw a few things! Checkout a few examples of <a href="https://secure.wikimedia.org/wikipedia/en/wiki/ASCII_art">ASCII art</a> &#8211; drawing on the screen with symbols instead of pixels for inspirations.</p>
<h2>Exercises</h2>
<p>1) Create <em>console.h</em> and <em>console.cpp</em> files in your project. Put functions’ declarations in the .h file and function implementations into .cpp file. Make sure to “add” these two files to all the other projects you will build for this lesson.<br />
2) Write <em>ConsoleGetCursor</em>(), <em>ConsoleSetCursor</em>(), <em>ConsolePrint</em>() and <em>ConsoleClear</em> () functions.<br />
3) Draw a picture of a tree in the middle of the screen (feel free to change it!):</p>
<pre style="padding-left: 30px;">\/  \/
 \  /
  \/
  ||</pre>
<p>4) Draw a car. Can you draw an animation of a car going from the left to the right side of the screen:</p>
<pre>   _
_/___\_
o     o</pre>
<p>5) Draw an animation of a man walking form the left to the right side of the screen:</p>
<pre>  0        0      0       0
 /|\      /|\    /|\     /|\
 / \       |\     |      /|</pre>
<p>6) Draw graphics of the following functions (use &#8216;*&#8217; for the points of the graph):</p>
<p style="padding-left: 30px;">a) y(x) = 5<br />
b) y(x) = x^2<br />
c) y(x) = sqrt(x)</p>
<p>7) Add rocket animation to the Lunar Lander game.</p>
<pre> / \
/   \
\   /
 |_|
/   \</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.aleksey.com/2011/04/20/lesson-10-drawing-on-the-console/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Lesson 9 &#8211; Three Ways to Pass Parameters To a Function</title>
		<link>http://www.aleksey.com/2011/04/06/lesson-9-three-ways-to-pass-parameters-to-a-function/</link>
		<comments>http://www.aleksey.com/2011/04/06/lesson-9-three-ways-to-pass-parameters-to-a-function/#comments</comments>
		<pubDate>Thu, 07 Apr 2011 00:36:16 +0000</pubDate>
		<dc:creator>Aleksey Sanin</dc:creator>
				<category><![CDATA[Practical Programming]]></category>

		<guid isPermaLink="false">http://www.aleksey.com/?p=194</guid>
		<description><![CDATA[Curiouser and curiouser! Lewis Carroll, Alice in Wonderland Practical Programming When you call a function and pass into the function values for the function’s input parameters, the C/C++ compiler creates a copy of all the input parameters’ values and only &#8230; <a href="http://www.aleksey.com/2011/04/06/lesson-9-three-ways-to-pass-parameters-to-a-function/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em>Curiouser and curiouser!</em><br />
<em>Lewis Carroll, Alice in Wonderland</em></p>
<p><a href="../2011/03/17/practical-programming/">Practical Programming</a></p>
<p>When you call a function and pass into the function values for the function’s input parameters, the C/C++ compiler creates a copy of all the input parameters’ values and only then calls a function to process these values. For example, if you have a function defined as</p>
<pre style="padding-left: 30px;">void DrawCircle(COORD p, int r);</pre>
<p>And you perform a call</p>
<pre style="padding-left: 30px;">COORD x = {10, 15};
DrawCircle(x, 23);</pre>
<p>Then the computer will perform the following steps:</p>
<ol>
<li>Allocate memory for input parameters x and r.</li>
<li>Copy values p =&gt; x, 23 =&gt; r.</li>
<li>Execute the function DrawCircle().</li>
</ol>
<p>This method of passing input parameters to a function is called <em>passing by value</em> because only values are passed into the function. It works great for built-in types since these types are small but it quickly becomes expensive for more complex <em>struct</em> types. It is not unusual to have a <em>struct</em> with several dozens fields. Allocating memory for a large <em>struct</em> and copying all the fields is a costly process. Thus, C/C++ language provides another methods for passing parameters to a function: <em>passing by reference </em>and <em>passing by pointer</em>.</p>
<p>To declare an input parameter as <em>passed by reference</em>, you need to put an ampersand ‘&amp;’ in front of the variable name in the function declaration:</p>
<pre style="padding-left: 30px;">void DrawCircle(COORD &amp; p, int r);</pre>
<p>When you call the function in the usual way:</p>
<pre style="padding-left: 30px;">COORD x = {10, 15};
DrawCircle(x, 23);</pre>
<p>The computer will no longer allocate memory for the input parameter <em>p</em> and will simply create a <em>reference</em> (alias) that maps variable<em> p</em> to the function’s input parameter <em>x</em>. Note that parameter <em>r</em> is still passed by value: it is just an integer and passing it by value is not slower than passing it by reference.</p>
<p>When you pass a parameter by reference, the function has access to the original variable and can modify it. This comes handy when you need to return multiple values from a function. For example, it is very common to have a function return a status code that indicates if there are any errors during function execution while the actual data is returned from a function through parameters passed by reference. For example, the following function will return status code from the function and the screen size will be returned in <em>sz</em> input parameter:</p>
<pre style="padding-left: 30px;">STATUS_CODE GetScreenSize(SIZE &amp; sz);
...
SIZE screenSize;
if(GetScreenSize(screenSize) == 0) {
    cout &lt;&lt; “Screen size: “ &lt;&lt; screenSize.w &lt;&lt; “ x ” &lt;&lt; screenSize.h &lt;&lt; endl;
} else {
    cout &lt;&lt; “Error getting screen size” &lt;&lt; endl;
}</pre>
<p>If the function doesn’t modify input parameters, it can declare this by using the <em>const</em> keyword. For example, the <em>DrawCircle</em> function doesn’t need to modify its parameters and we can declare it as follows (note that there is no point in using <em>const</em> keyword for parameters passed by value because function can’t modify the variables regardless):</p>
<pre style="padding-left: 30px;">void DrawCircle(const COORD &amp; p, int r);</pre>
<p>It is usually a good idea to always mark with <em>const</em> the input parameters that the function doesn’t modify. This gives a extra clue to the compiler and the developer of how this function should be used and it helps to avoid stupid mistakes.</p>
<p>The last but not the least option for passing input parameters is <em>passing by pointer</em>. It is very similar to passing by reference: no value copying happens, the function gets access to the variable passed into the function and can potentially modify it. The syntax for <em>passing by pointer</em> is a little bit more complex than syntax for passing by reference and requires changes for function declaration and function call. The star ‘*’ is used in the function declaration to indicate that this parameter is passed by pointer and ampersand ‘&amp;’ is used during the function call to get a pointer from a variable:</p>
<pre style="padding-left: 30px;">STATUS_CODE GetScreenSize(SIZE *sz);
...
SIZE screenSize;
if(GetScreenSize(&amp;screenSize) == 0) {
    cout &lt;&lt; “Screen size: “ &lt;&lt; screenSize.w &lt;&lt; “ x ” &lt;&lt; screenSize.h &lt;&lt; endl;
} else {
    cout &lt;&lt; “Error getting screen size” &lt;&lt; endl;
}</pre>
<p>This is probably somewhat confusing but we are going to discuss pointers in great details later. <em>Passing by reference</em> is the preferred C++ way to avoid input parameters copying or return extra data from a function .<em> Passing by pointers</em> is the “old” C way used in C libraries and APIs (for example, Windows API is a C API).</p>
<h2>Exercises</h2>
<p>1) Look at the following functions and describe how input parameters are passed in and which parameters can be modified by the function:</p>
<pre style="padding-left: 30px;">bool GetScreenInfo(HANDLE hScreen, SCREEN_INFO &amp; info);
bool SetScreenInfo(HANDLE hScreen, const SCREEN_INFO &amp; info);
bool GetScreenInfo(HANDLE hScreen, SCREEN_INFO * info);
bool SetScreenInfo(HANDLE hScreen, SCREEN_INFO const * info);</pre>
<p>2) On a piece of paper, write example of how you would call each of the functions from 1).</p>
<p>3) Describe the meaning of the parameters for the &#8220;main&#8221; function (note that &#8220;char *&#8221; type is a string and that &#8220;char **&#8221; is simply a pointer to a string):</p>
<pre style="padding-left: 30px;">int main(int argc, char const ** argv);</pre>
<p>4) Modify the Lunar Lander program and use passing by reference where appropriate. Don’t forget to use const keyword when function doesn’t modify input parameters passed by reference.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.aleksey.com/2011/04/06/lesson-9-three-ways-to-pass-parameters-to-a-function/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Lesson 8 &#8211; Defining Your Own Data Types: struct</title>
		<link>http://www.aleksey.com/2011/03/30/lesson-8-defining-your-own-data-types-struct/</link>
		<comments>http://www.aleksey.com/2011/03/30/lesson-8-defining-your-own-data-types-struct/#comments</comments>
		<pubDate>Wed, 30 Mar 2011 21:46:43 +0000</pubDate>
		<dc:creator>Aleksey Sanin</dc:creator>
				<category><![CDATA[Practical Programming]]></category>

		<guid isPermaLink="false">http://www.aleksey.com/?p=186</guid>
		<description><![CDATA[The difference between a bad programmer and a good one is whether he considers his code or his data structures more important. Bad programmers worry about the code. Good programmers worry about data structures and their relationships. Linus Torvalds Practical &#8230; <a href="http://www.aleksey.com/2011/03/30/lesson-8-defining-your-own-data-types-struct/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em>The difference between a bad programmer and a good one is whether he considers his code or his data structures more important. Bad programmers worry about the code. Good programmers worry about data structures and their relationships.</em><br />
<em><a href="http://en.wikipedia.org/wiki/Linus_Torvalds">Linus Torvalds</a></em></p>
<p><a href="../2011/03/17/practical-programming/">Practical Programming</a></p>
<p>In addition to fundamental types built into the language (integer, float, character, &#8230;) the C/C++ language allows you to create custom types. Custom types are used to combine related variables and to extend the C/C++ language to simplify it and make it easier to use when solving a particular problem. For example, if you are writing an application that draws pictures on the computer screen, then many of your functions will require screen coordinates (x, y) as the input parameters:</p>
<pre style="padding-left: 30px;">// draw a line between points (x1,y1) and (x2,y2);
void DrawLine(int x1, int y1, int x2, int y2);

// draw a circle of radius r with center in point (x,y)
void DrawCircle(int x, int y, int r);</pre>
<p>Repeating “int x, int y” everywhere is confusing and error prone. Can you understand the following code without looking at the functions definitions?</p>
<pre style="padding-left: 30px;">DrawLine(114, 124, 125, 565); // is it x1, y1, x2, y2 or x1, x2, y1, y2 or ???
DrawCircle(56, 42, 67); // where is radius? first? or last? or in the middle?</pre>
<p>Instead, you can define a new custom type <em>COORD</em> using the <em>struct</em> keyword. In our new type the two individual coordinates are “combined” together to create a new entity:</p>
<pre style="padding-left: 30px;">struct COORD {
  int x;
  int y;
};</pre>
<p>We can use our new data type anywhere we use built-in types:</p>
<pre style="padding-left: 30px;">// draw a line between points p1 and p2
void DrawLine(struct COORD p1, struct COORD p2);  

// draw a circle of radius r with center in point p
void DrawCircle(struct COORD p, int r); 

... 

struct COORD p1 = { 114, 124 };
struct COORD p2 = { 125, 565 };
struct COORD p3 = { 56, 42 };

DrawLine(p1, p2);
DrawCircle(p3, 67);</pre>
<p>You can access individual “fields” in the structure by using the “dot” notation:</p>
<pre style="padding-left: 30px;">struct COORD p;

p.x = 123;
p.y = 124;

cout &lt;&lt; “The coordinates are x = “ &lt;&lt; p.x &lt;&lt; “ and y = “ &lt;&lt; p.y &lt;&lt; endl;
if(p.x &gt; p.y) {
  cout &lt;&lt; “The x coordinate is greater than y” &lt;&lt; endl;
} else if(p.y &gt; p.x) {
  cout &lt;&lt; “The y coordinate is greater than x” &lt;&lt; endl;
}</pre>
<p>The structures are simple collection of individual fields and can include fields of different types (including other structures themselves!):</p>
<pre style="padding-left: 30px;">// define a structure for a circle: center point + radius
struct CIRCLE {
  COORD center_point;
  int radius;
};

// define size of something: two fields - witdh (w) and height (h)
struct SIZE {
  int w;
  int h;
};

// define a structure for a rectangle: top left corner + size
struct RECT {
  COORD top_left_corner;
  SIZE size;
};</pre>
<p>To access fields in complex data structures, simply use the “dot” on each &#8220;level&#8221;:</p>
<pre style="padding-left: 30px;">struct RECT foo;
foo. top_left_corner.x = 120;
foo. top_left_corner.y = 435;
foo. size.w = 14;
foo. size.h = 94;</pre>
<p>Finally, to make the code look nicer, you can use “<em>typedef</em>” to assign an alternative name (alias) to a type (and remove the need to use “<em>struct</em>” keyword everywhere!):</p>
<pre style="padding-left: 30px;">typedef struct CIRCLE CIRCLE;

...

void DrawCircle(CIRCLE c);

...

CIRCLE c;
c.center.x = 56;
c.center.y = 89;
c.radius = 10;
DrawCircle(c);</pre>
<p>You can even use typedef and struct together in one statement!</p>
<pre style="padding-left: 30px;">typedef struct COORD {
  int x;
  int y;
} COORD;</pre>
<p>In this example the “<em>struct COORD { &#8230; }</em>” part defines the type and the rest is a standard &#8220;<em>typedef</em>&#8220;.</p>
<p>You can use typedef to assign an alias to any type including the built-in types. For example, to make a program more readable you can <em>typedef</em> integer type to a special <em>ERROR_CODE</em> type to clearly distinguish error codes from all other possible usages for integers:</p>
<pre style="padding-left: 30px;">typedef int ERROR_CODE;

ERROR_CODE DoSomething(); // the function returns an error code, nothing else!</pre>
<p>Using <em>struct</em> and <em>typedef</em> allows a programmer to “customize” the C/C++ language and create better <em>abstractions</em> for solving a particular problem. In the future, we will be looking at different <em>libraries</em> (collections of functions) that can be used as building blocks for simplifying common tasks. All the good libraries extensively use <em>struct</em> and <em>typedef</em> to provide a simple yet powerful <em>interface</em> for developers.</p>
<p>Usually the data structures design is hard to change and it lives longer than the algorithm. A good data structures design makes programming easy and enjoyable. A bad data structures design leads to nightmares and bugs in the code.</p>
<h2>Exercises</h2>
<p>1) Write a function that calculates a distance between two given points.<br />
2) Write a function that calculates the middle point between the two given points.<br />
3) Write functions that calculates the area of a circle and a rectangle.<br />
4) Define structures for 3-dimensional coordinates, a sphere, and a cube. Write functions to calculate volume of a sphere and a cube.<br />
5) Define a data structure for  a Lunar Module from the game you wrote. Refactor the game to use the new data structure. Try to separate the code responsible for game physics from the code that reads/writes data to/from user.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.aleksey.com/2011/03/30/lesson-8-defining-your-own-data-types-struct/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Lesson 7 &#8211; Functions and Header Files</title>
		<link>http://www.aleksey.com/2011/03/23/lesson-7-functions-and-header-files/</link>
		<comments>http://www.aleksey.com/2011/03/23/lesson-7-functions-and-header-files/#comments</comments>
		<pubDate>Thu, 24 Mar 2011 03:18:45 +0000</pubDate>
		<dc:creator>Aleksey Sanin</dc:creator>
				<category><![CDATA[Practical Programming]]></category>

		<guid isPermaLink="false">http://www.aleksey.com/?p=176</guid>
		<description><![CDATA[Divide and conquer! Latin Idiom Practical Programming You are already familiar with the main() function (_tmain() in Visual Studio dialiect). This is a special function that is automatically executed when program starts. As your program gets bigger, the main() function &#8230; <a href="http://www.aleksey.com/2011/03/23/lesson-7-functions-and-header-files/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em>Divide and conquer!<br />
Latin Idiom</em><br />
<a href="../2011/03/17/practical-programming/"></a></p>
<p><a href="../2011/03/17/practical-programming/">Practical Programming</a></p>
<p>You are already familiar with the <em>main</em>() function (_<em>tmain</em>() in Visual Studio dialiect). This is a special function that is automatically executed when program starts. As your program gets bigger, the <em>main</em>() function grows and it gets harder and harder to understand the code. You can fight the complexity by creating your own custom functions. You break apart your code and make it easier to understand.</p>
<p>As with everything else in C/C++, you must define a function before you can use it. Let’s take a look at this example:</p>
<pre style="padding-left: 30px;">// a function that calculates factorial
int factorial(int n) {
    int res = 1;
    int ii;

    for(ii = 1; ii &lt;= n; ++ii) {
        res = res * ii;
    }
    return res;
}</pre>
<p>This function calculates a factorial of the integer number. After you defined a function, you can call it with different actual parameters:</p>
<pre style="padding-left: 30px;">int main(int argc, char** argv) {
    int z;

    z = factorial(10);
    cout &lt;&lt; “Factorial of 10 is “ &lt;&lt; z &lt;&lt; endl;

    cout &lt;&lt; “Enter a number:” &lt;&lt; endl;
    cin &gt;&gt; z;
    cout &lt;&lt; “Factorial of “ &lt;&lt; z &lt;&lt; “ is “ &lt;&lt; factorial(z) &lt;&lt; endl;

    return 0;
}</pre>
<p>The function definition consists of the following items:</p>
<ul>
<li> the function <em>name</em> (similar to variable names rules apply: function name must start from a letter, contain only letters, digits and underscore ‘_’ and be unique);</li>
<li> the function <em>input parameters</em> definition (what functions expects);</li>
<li> the function <em>return type</em> (what should be expected back);</li>
<li> the function <em>implementation</em> (<em>body</em>).</li>
</ul>
<pre style="padding-left: 30px;"><em>return_type function_name</em>(<em>input_parameters_list</em>) {
    <em>function_implementation</em>
}</pre>
<p>Our factorial function from the example above has name “<em>factorial</em>”, it requires one integer input parameter (“<em>int n</em>”) and returns an integer (“<em>int</em>”).</p>
<p>A special return type “<em>void</em>” is used to indicate that a function has no return parameters:</p>
<pre style="padding-left: 30px;">void print_result(int step, float res) {
    cout &lt;&lt; “On step “ &lt;&lt; ii &lt;&lt; “ the result is “ &lt;&lt; res &lt;&lt; endl;
}</pre>
<p>This function has two input parameters: first of type <em>int</em> and second of type <em>float</em>. When you call a function you must make sure that actual parameters have correct types:</p>
<pre style="padding-left: 30px;">print_result(10, 0.345); // correct
print_result(11, “some string”); // incorrect: compiler error “type mismatch”</pre>
<p>A special keyword “<em>return</em>” is used inside the function body to stop the function execution immediately and return the value to the caller. A non-void function must return a value on all execution paths. The following function will generate compiler error: if a is equal to b then there is no “<em>return</em>” value:</p>
<pre style="padding-left: 30px;">int foo(int a, int b) {
    if(a &lt; b) {
        cout &lt;&lt; “a is less than b” &lt;&lt; endl;
        return -1;
    } else if(a &gt; b) {
        cout &lt;&lt; “a is greatre than b” &lt;&lt; endl;
        return 1;
    }

    cout &lt;&lt; “a is equal to b” &lt;&lt; endl;
    // compiler error - no return value!!!
 }</pre>
<p>A void function can use <em>return</em> statement to exit from the function early w/o returning anything:</p>
<pre style="padding-left: 30px;">void bar(int x) {
    if(x &lt;= 0) {
        return; //  if x &lt;= 0 then function stops here
     }
     cout &lt;&lt; “The x is positive” &lt;&lt; endl;
}</pre>
<p>When you are doing step-by-step debugging of a program with functions, you can either <em>step over</em> the function call or <em>step into</em> the function call to execute a function step-by-step with actual parameters for this call.</p>
<p>Large programs contain multiple files. To make defined functions from one file visible in another file, programmers separate function declaration and function implementation. The function declaration is placed in a <em>header</em> file (which usually has .h extension):</p>
<pre style="padding-left: 30px;">// File factorial.h

int factorial(int n);</pre>
<p>and function implementation in the <em>source</em> file (which usually has .cpp extension):</p>
<pre style="padding-left: 30px;">// File factorial.c

#include “factorial.h”

// a function that calculates factorial
int factorial(int n) {
    int res = 1;
    int ii;
    for(ii = 1; ii &lt;= n; ++ii) {
        res = res * ii;
    }
    return res;
}</pre>
<p>The <em>include</em> command is used to insert into the current file the content of included file “as-is”. Now you can use your function anywhere!</p>
<pre>// File program.cpp
#include “factorial.h”

int main(int argc, char* argv[]) {
   cout &lt;&lt; “Factorial of 10 is “ &lt;&lt; factorial(10) &lt;&lt; endl;
}</pre>
<p>You probably noticed that we’ve used include command before to load function definitions from the standard C/C++ libraries:</p>
<pre style="padding-left: 30px;">#include &lt;iostream&gt;
#include &lt;stdlib.h&gt;
#include &lt;math.h&gt;</pre>
<p>Note that we used quotes to load our custom header file</p>
<pre style="padding-left: 30px;">#include “factorial.h”</pre>
<p>and less/greater brackets to load standard C/C++ header files. The reason for this difference is the C/C++ compiler algorithm for locating the correct file on disk. For now, just follow this convention: custom header files from the same project should be included with quotes and standard header files from C/C++, Windows, etc. should be included with less/greater brackets.</p>
<p>The process of modifying the source code to make it more readable and more maintainable is called re-factoring. Separating the code into re-usable functions and breaking apart big files into smaller files is one of the easiest ways to re-factor your code.</p>
<h2>Exercises</h2>
<p>1 ) Re-factor your Fibonacci program and create a function for calculating the Fibonacci number.<br />
2) Re-factor your GCD (greatest common divisor) program and create a function for calculating the GCD.<br />
3) Re-factor your factorial program and create a separate header/source files for the factorial function. Use “Project” / “Add File” menu in Visual Studio to create new files. Don’t forget to add new files to git before committing your changes!</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.aleksey.com/2011/03/23/lesson-7-functions-and-header-files/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Lesson 6: Source Control System &#8211; GIT</title>
		<link>http://www.aleksey.com/2011/03/22/lesson-6-source-control-system-git/</link>
		<comments>http://www.aleksey.com/2011/03/22/lesson-6-source-control-system-git/#comments</comments>
		<pubDate>Wed, 23 Mar 2011 03:14:19 +0000</pubDate>
		<dc:creator>Aleksey Sanin</dc:creator>
				<category><![CDATA[Practical Programming]]></category>

		<guid isPermaLink="false">http://www.aleksey.com/?p=146</guid>
		<description><![CDATA[Better be safe than sorry! English Idiom Practical Programming Writing a program is usually a trial-and-error affair. Thus, it is really important to be able to easily undo your changes and rollback to the previously known good version. In the &#8230; <a href="http://www.aleksey.com/2011/03/22/lesson-6-source-control-system-git/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><em>Better be safe than sorry!</em><br />
<em>English Idiom</em></p>
<p><a href="../2011/03/17/practical-programming/">Practical Programming</a></p>
<p>Writing a program is usually a trial-and-error affair. Thus, it is really important to be able to easily undo your changes and rollback to the previously known good version. In the early days of programming, this was achieved by creating a complete copy of a project. Today, we have source control systems that simplify and optimize this process.</p>
<p>A source control system (SCM) tracks changes in a set of files (a project). To record your changes in the SCM, you execute a commit operation. After you commit you changes, you can quickly go back to the exact state you’ve been at the time of the commit.</p>
<p>We are going to use <em>git</em> as our primary SCM (there are many others!). Git has many interesting features but we will start from basics. To install <em>git</em>, install <a href="http://cygwin.org/">Cygwin</a> &#8211; set of command line tools for Windows. Make sure to mark <em>git</em> package for installation!</p>
<p>First, you will need to tell git who you are. You will need to do this step only once. Open the Windows console (run <em>cmd.exe</em>) or a Cygwin shell window and execute the following commands:</p>
<pre style="padding-left: 30px;">git config --global user.name “&lt;your name&gt;”
git config --global user.email “&lt;your email&gt;”</pre>
<p>If you like pretty highlighting, then don&#8217;t forget to configure git to use colors:</p>
<pre style="padding-left: 30px;">git config --global color.status auto
git config --global color.branch auto</pre>
<p>Next, you will need to create a git repository for one of your projects:</p>
<pre style="padding-left: 30px;">cd &lt;your project folder&gt;
git init</pre>
<p>Right now the repository is empty. Let’s add your source files to git. There is no need to add files produced by the compiler/linker (usually, they will be placed into <em>Debug</em> sub-folder), they can be re-created. However, don’t forget to add your Visual Studio project files. If you will add new files to your project in the future, make sure to add them to git!</p>
<pre style="padding-left: 30px;">git add &lt;list of files to add&gt;</pre>
<p>Now is the most important step. Let’s commit your changes and save them permanently. For every commit, you specify a “commit message” (specified after <em>-m</em> flag) that briefly describe your changes. It is important to have good descriptive commit messages to make sure you can figure out what you’ve changed long time after you made the change):</p>
<pre style="padding-left: 30px;">git commit -a -m “Initial commit”</pre>
<p>The -a command line option tells the git to commit all changed files you&#8217;ve previously added. You can also commit just some files</p>
<pre style="padding-left: 30px;">git commit -m “&lt;commit message&gt;” &lt;list of files to commit&gt;</pre>
<p>To verify our commit, let’s check the log</p>
<pre style="padding-left: 30px;">git log</pre>
<p>This command will print the commit ID (long string of numbers and letters), the commit author (you!), the commit date and the commit message (“Initial commit”).</p>
<p>When you are working on a project, you can view what did you change since last commit. This is very useful and helpful tool:</p>
<pre style="padding-left: 30px;">git status
git diff</pre>
<p>At any moment, you can “undo” your current changes (they will be lost!) and get  a previously committed version of a file:</p>
<pre style="padding-left: 30px;">git checkout &lt;filename&gt;</pre>
<p>Finally, you can easily <strong>add</strong>/<strong>c</strong>o<strong>p</strong>y/<strong>m</strong>o<strong>v</strong>e/<strong>r</strong>e<strong>m</strong>ove files in git using the following commands:</p>
<pre style="padding-left: 30px;">git add &lt;filename&gt;
git cp &lt;filename&gt;
git mv &lt;filename&gt;
git rm &lt;filename&gt;</pre>
<p>To use git to its full advantage, make sure to add all your files to git and commit every time you feel the change you just made is working. There is no harm in having too many commits!</p>
<h2>Exercises</h2>
<p>1) Create git repositories to 3-4 of your projects. Make sure to add Lunar Model game!<br />
2) For one of the projects try to</p>
<ul>
<li> modify one or more files;</li>
<li> view diff of your changes;</li>
<li> commit your changes;</li>
<li> view the log of your commits.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.aleksey.com/2011/03/22/lesson-6-source-control-system-git/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

