Apr 192012
 

Expanding on the lessons learnt from the previous post regarding a basic program, even something that simple can still be put together in slightly different ways with regards to the ” std ” library.


// You Have Won The Game!
// My first C++ program.

#include <iostream>

int main()
    {
        std::cout << "You Have Won The Game!" << std::endl;
        return 0;
    }

This is the same program covered in this blog post.

The following are variations of this same program, that make use of the ” using ” directive, which in this case drives the program to get access to parts of the ” std ” namespace directly. Remembering the postcode analogy from this blog post then the ” using ” directive tells the program to act like the objects in the ” std ” namespace are all on the same road, so it doesn’t need to constantly need the ” std “namespace to be invoked to know where to look for the objects as it already knows which namespace they are in.


// You Have Won The Game! 2.0
// My first C++ program redux.

#include <iostream>
using namespace std;

int main()
{
cout << "You Have Won The Game!" << endl;
return 0;
}

In this example, the using directive tells the program that it will be using the ” Std ” namespace in this line here:

using namespace std;

so that this line:

cout << "You Have Won The Game!" << endl;

does not require the ” cout ” and ” endl ” objects do not need the ” Std:: ” prefix as it already knows that the objects being called are part of the ” std ” namespace.


// You Have Won The Game! 3.0
// My first C++ program redux.

#include <iostream>
using std::cout;
using std::endl;

int main()
{
cout << "You Have Won The Game!" << endl;
return 0;
}

In this 3rd example, the lines here:


using std::cout;
using std::endl;

Tell the program the exact object in the namespace that will be called, so instead of loading all the object in the namespace, it knows that it only needs these two, stopping the compiler from making a local copy of all the objects and elements in the ” std ” namespace.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>