Sunday, 13 May 2018

Chapter 8 // Exercise 14 - Principles & Practice Using C++

In this exercise I am using Visual Studio Community 2017 and the header file "std_lib_facilities.h" which can be found here:

http://www.stroustrup.com/Programming/PPP2code/std_lib_facilities.h


Chapter 8 // Exercise 14



14. Can we declare a non-reference function argument const (e.g., void f(const int);)? What might that mean? Why might we want to do that? Why don't people do that often? Try it; write a couple of small programs to see what works.


#include "stdafx.h"
#include "std_lib_facilities.h"

void f(const int);

int main()
{
 int n1 = 1;
 const int n2 = 2;

 f(n1);
 f(n2);
 f(3);

 keep_window_open();

 return 0;
}

void f(const int i)
{
 cout << i << endl;
}

You can declare a non-reference argument const. As you cannot change the value it is only really useful for printing to the screen or extracting data for other calculations. 

And thus concludes Chapter 8. When I first read this chapter almost a year and a half ago now, I honestly couldn't wrap my head around pointers and pass-by-value/reference. I just thought I wasn't going to get it. Then I had to build engines using DirectX9 and DirectX11 and everything is a pointer. The more time I spend programming the more comfortable I feel using more advanced concepts. However, going back to the basics is useful as there are many things in this chapter I've implemented in my code. I kept passing the d3d device by reference between classes, that's now a pointer instead. The next chapter is about classes which I needed as I feel like I needed to seriously brush up.

No comments:

Post a Comment