Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers in CPP, confusion regarding an example program

Tags:

c++

pointers

Working my way through accelerated c++. There's an example where there are multiple things that I do not understand.

double grade = 88;

static const double numbers[] = { 97,94,90,87,84,80,77,74,70,60,0 };

static const char* const letters[] = { "A+","A","A-","B+","B","B-","C+","C","C-","D","F" };

static const size_t ngrades = sizeof(numbers) / sizeof(*numbers);

for (size_t i = 0;i < ngrades;++i) {
    if (grade >= numbers[i]) {
        cout << letters[i];
        break;
    }
}
  1. I don't understand what's going on with static const char* const letters[] = (...). First of all, I always thought a char was a single character delimited by '. Single or more characters delimited by " are for me a string.
  2. The way I've understood pointers is that they're a value that represents the address of an object, although this would be initialized as int* p=&x;. They have the advantage of being able to be used like an iterator (kind of). But I really do not get what is going on here, we declare a pointer letters that gets assigned to it an array of values (not addresses), what does that mean? What would be a reason for doing this?
  3. I know what static is in java, is the meaning similar in CPP? The author writes it means that the compiler will initialize the static values only once. But isn't that done with every variable within a certain scope? I've noticed in debug that I seem to skip over the values after having executed it the first time. But that would imply that even after my program is finished running these static values are still saved? That doesn't seem logical to me.
like image 806
Nimitz14 Avatar asked Jan 25 '26 10:01

Nimitz14


1 Answers

Regarding your first question, a string literal (like e.g. "A+") is an (read-only) array of characters, and as all arrays they can decay to pointers to their first element, i.e. a pointer to char. The variable letters is an array of constant pointers (the pointer in the array can't be changed) to characters that are constant.

For the third questions, what static means is different depending on which scope you declare the variable in. It's a linkage specifier when used in the global scope, and means that the variable (or function) will not be exported from the translation unit. If use for a variable in local scope (i.e. inside a function) then variable will be shared between invocations of the function, i.e. all calls to the function will have the same variable with the the value of it being kept between calls. Declaring a class-member as static means that it's shared between all object instances of the class.

like image 97
Some programmer dude Avatar answered Jan 27 '26 23:01

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!