0

entire code is below link. base64 decode snippet in c++ I have a question about const pointer in above link code.

main

std::vector<BYTE> myData;
...
std::string encodedData = base64_encode(&myData[0], myData.size());

base64_encode

std::string base64_encode(BYTE const* buf, unsigned int bufLen) {
  std::string ret;
  int i = 0;
  int j = 0;
  BYTE char_array_3[3];
  BYTE char_array_4[4];

  while (bufLen--) {
    char_array_3[i++] = *(buf++);
    if (i == 3) {

parameter is BYTE const* buf, not const BYTE* buf.

when const BYTE* buf is used as parameter, const is for BYTE, so pointer can be changed but the value of buffer can not be changed.

when BYTE const* buf is used, const is for pointer variable, so value can be changed but address can not be changed.

in above code, buf pointer is const, but buf++ is possible?

and why BYTE const* buf is used instead of const BYTE* buf?

thanks

user225549
  • 177
  • 2
  • 9
  • Loosely related: Here'a neat tool for helping figure out what "C gibberish" really means: https://cdecl.org/ – user4581301 Aug 30 '19 at 01:47
  • 1
    The rule is that `const` binds to the thing to its immediate *left*... unless `const` is the first thing, in which case (as an exception to the general rule) it binds to the thing to its immediate *right*. – Eljay Aug 30 '19 at 01:51

1 Answers1

1

Confusingly, const BYTE* and BYTE const* are equivalent to each other. Both are pointers-to-const.

To make the pointer itself const, the formulation is BYTE *const. A const pointer-to-const would be BYTE const *const or const BYTE *const.

I cannot speculate as to why the authors of this function chose the BYTE const* version instead of the much more popular const BYTE*.

Jack C.
  • 744
  • 3
  • 7
  • Why do you think `const BYTE*` is more popular? – eerorika Aug 30 '19 at 01:41
  • In `BYTE const * buf`, the `const` applies to the item before (`BYTE` is `const`). With `BYTE * const buf` the `const` item, the pointer , is also before the `const` . This makes `const BYTE * buf` the outlier. – user4581301 Aug 30 '19 at 01:43
  • thank you I coufused BYTE const * and const BYTE * are same. I confused with BYTE* const buf and const BYTE* buf. thanks a lot. – user225549 Aug 30 '19 at 02:03
  • 1
    @eerorika: I made that observation based on my experience reading C++. – Jack C. Aug 30 '19 at 02:37
  • It's much more common in the code I've found `const T` than `T const` because it's also more human readable. You'd usually say "a constant string" and not a "a string constant" although both mean the same. Saying "a string constant pointer" is confusing (both in C and in some human languages, at least in spanish adjectives could be before or after a noun) imho. – Mirko Aug 30 '19 at 03:46