iCodeLikeImDrunk
iCodeLikeImDrunk

Reputation: 17866

how does namespace and private variables work in assembly?

how does it work? are the variables stored in special registers or memory? im looking at the register/memory windows in visual but i cant understand it :(

#include <iostream>
using namespace std;

namespace first
{
  int x = 5;
  int y = 10;
}

namespace second
{
  double x = 3.1416;
  double y = 2.7183;
}

int main () {
  using first::x;
  using second::y;
  cout << x << endl;
  cout << y << endl;
  cout << first::y << endl;
  cout << second::x << endl;
  return 0;
}


class CRectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area (void);
  private:
    int param;
  } rect;

Upvotes: 1

Views: 1257

Answers (3)

wallyk
wallyk

Reputation: 57794

The compiler takes

namespace first
{
  int x = 5;
  int y = 10;
}

namespace second
{
  double x = 3.1416;
  double y = 2.7183;
}

and effectively produces assembly code which works something like this:

_first@@x:     dd      5
_first@@y:     dd      10
_second@@x:    dq      3.1416
_second@@y:    dq      2.7183

In case you are not familiar with assembly language, these four statements each reserve memory, two for 32-bit integers, and two for a floating point values, and assign labels to them. A label is a memory address.

Note that the namespace qualifies each variable name. The @ in itself it has no meaning, but escapes the namespace and variable name to isolate unusually named C++ language variables. Assembly language identifiers typically allow a greater range of characters in them than high level languages, convenient in usages such as this.

Upvotes: 3

chrisaycock
chrisaycock

Reputation: 37928

From the machine's perspective, there's nothing different about private or namespace. Those are just identifiers for the compiler. That is, the compiler enforces access rules, which is why you get compiler errors for doing something you shouldn't. The binary code the compiler ultimately produces, however, doesn't make any distinction about what the data is.

Upvotes: 8

nikola-miljkovic
nikola-miljkovic

Reputation: 670

Namespaces are used as direction for compiler, as actual var names and method/class names have different name after compilation, so namespace name is not used.

Upvotes: 1

Related Questions