Back to slide -- Keyboard shortcut: 'u'        next -- Keyboard shortcut: 'n'          namespaces/namespace-1.cc - Illustration of using declarations and using directives - by example.Lecture 3 - slide 22 : 27
Program 1

// Reproduced from page 847 of 'The C++ Programming Language' (3ed).
// Shows 'using directives' and 'using declarations' by examples.

#include <iostream>
#include <string>

namespace X {
  int i = 10, j = 11, k = 12;
}

int k;                // Global variable

void f1(){            // Illustrates using directives
  int i = 0;
  using namespace X;  // A using directive makes i, j, and k from X accessible
  i++;                // local i
  j++;                // X::j
  k++;                // X::k or ::k   The name k is ambiguous
  ::k++;              // global k
  X::k++;             // X::k
}

void f2(){            // Illustrates using declarations
  int i = 0;
  using X::i;         // double definition: i already defined in this scope
  using X::j;       
  using X::k;         // hides global k

  i++;                // local i
  j++;                // X::j
  k++;                // X::k
}

int main(){
  f1();
  f2();
}