-1

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

2
  • Loosely related: Here'a neat tool for helping figure out what "C gibberish" really means: cdecl.org Commented Aug 30, 2019 at 1: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. Commented Aug 30, 2019 at 1:51

1 Answer 1

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*.

Sign up to request clarification or add additional context in comments.

5 Comments

Why do you think const BYTE* is more popular?
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.
thank you I coufused BYTE const * and const BYTE * are same. I confused with BYTE* const buf and const BYTE* buf. thanks a lot.
@eerorika: I made that observation based on my experience reading C++.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.