0

After a couple of days of Googling, I've finally given up and need some help from the community.

I'm quite new to C++, and decided I'd start by dissecting this code:

A C++ program to get CPU usage from command line in Linux

For the most part, I can surmise a good bit of it, except how the ampersand is being used in the last line:

const int NUM_CPU_STATES = 10;

typedef struct CPUData {
    std::string cpu;
    size_t times [NUM_CPU_STATES];
} CPUData;

std::vector<CPUData> entries1;

const CPUData & e1 = entries[$i]

The closest I can gather is that its a Bitmask or Bitwise operator. But either way, I can't make sense of how its used in this context.

EDIT: Thanks for the quick replies! I understand now that this is creating a reference. What kept me from picking up on it was the spacing, given the nuances of any language I had assumed it had some significant meaning.

Greg
  • 3
  • 2
  • 2
    You're better off getting a good book on C++, rather than trying to dissect random snippets of code. Any good book would unveil the meaning of this quite quickly, and if you're serious about learning C++ you will thank yourself. FWIW though https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in?rq=1 should answer your question – Tas May 22 '19 at 00:21
  • The ampersand here is used to create a reference. A simple way of explaining a reference is it is used to alias another variable. In this case the variable e1 is used to alias entries[$i]. A const reference means that you cannot use e1 to change the value of entries[$i] – Rahul Kadukar May 22 '19 at 00:21
  • 1
    About your edit: C++ in general doesn't care about spaces. In the past there was at least one case where they mattered (`vector>` was not accepted, you had to put a space between the two `>` to avoid confusion with the right-shift operator `>>`), but that was changed some years ago (with C++11 if I'm not wrong). By the way, whether you should write `int& a`, `int &a` or `int & a` (and likewise for pointers, using `*` instead of `&`) is subject of endless religious wars. – Fabio says Reinstate Monica May 22 '19 at 01:19

1 Answers1

0

It's declaring a constant reference.

/* data type */  /* varname */    /* data we are referencing */
const CPUData&        e1      =   entries[i]

So e1 directly refers to the item 'entries[i]'

robthebloke
  • 9,331
  • 9
  • 12