-3

Can someone explain why it is possible to declare a const pointer to something that has a different value for each iteration of the loop?

#include <assimp/Importer.hpp>
...

for (int i = 0; i < N; i++) {
    const aiVector3D* vp = &(mesh->mVertices[i]);
    // use vp.x ...
}

This snippet is part of an example code of how to use assimp to import mesh-data. (i am new to c++)

ultralord
  • 33
  • 1
  • 4
  • `const` just means that the compiler will not allow *you* to change the value. `int i = 0; const int * p = &i; ++(*p) /* error */; ++i /* ok */;` – Erik Apr 28 '15 at 15:17
  • 1
    I think there's also a misconception about what `const aiVector3D* vp` means vs. `aiVector3D* const vp`. – JimmyB Apr 28 '15 at 15:43
  • Right, in the example, it's NOT a const pointer; it's a pointer to a const object. There is a big difference. http://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const – Dan Korn Apr 28 '15 at 16:02

1 Answers1

2

Its because vp gets destroyed and redeclared every iteration. It's not that it's pointing to a different variable each time, it's a completely different pointer.

quamrana
  • 37,849
  • 12
  • 53
  • 71
David Haim
  • 25,446
  • 3
  • 44
  • 78
  • it doesn't invalidate the answer. – David Haim Apr 28 '15 at 15:29
  • in order to extract a value but not alter it in any way, or because the API he uses obligates him to pass const pointer , or many other reasons for why use `const` in C++ – David Haim Apr 28 '15 at 15:34
  • @ultralord Because it expresses the intent of the programmer and prevents mistakes. By declaraing `vp` as `const`, you're indicating that you only need to read its value within the body of the for-loop, and the compiler will complain if you accidentally attempt to do otherwise. – Julian Apr 28 '15 at 15:59
  • No, this answer is incorrect. It's NOT a const pointer. It's a non-const pointer to a const object. The same non-const pointer can be modified to point to a different const object. – Dan Korn Apr 28 '15 at 16:03