Note that there are some explanatory texts on larger screens.

plurals
  1. POReturning a void pointer to a constant object in C
    text
    copied!<p>I'm writing an access function which returns a pointer to an internal buffer and I'd like to hint to users of my function that they shouldn't update the object that's pointed to. A very contrived example would be:</p> <pre><code>void myAccessFunc(bool string, void* p, size_t* len) { static const char* s = "aha!"; static const int i = 123; if (string) { *(char**)p = &amp;s; *len = strlen(s); } else { *(int**)p = &amp;i; *len = sizeof(i); } } char* s; size_t bytes; myAccessFunc(true,&amp;s, &amp;bytes); printf("Got '%s'\n", s); </code></pre> <p>Yes, I know that looks flakey.</p> <p>What I want to prevent is:</p> <pre><code>char* s; size_t bytes; myAccessFunc(true,&amp;s,&amp;bytes); s[4] = '?'; </code></pre> <p>I know I can't completely prevent it but I'd at least like the compiler warning to hint to a user that they shouldn't be doing that. If they cast my pointer, then that's their problem. Is there some combination of const and void and * that will do this? I tried something like:</p> <pre><code>void myAccessFunc(bool string, const void** p, size_t* len); </code></pre> <p>but it seemed do away with the voidness of the pointer so a caller had to do:</p> <pre><code>const void* p; size_t bytes; myAccessFunc(true, &amp;p, &amp;bytes); </code></pre> <p>or</p> <pre><code>const char* s; size_t bytes; myAccessFunc(true, (const void**)&amp;s, &amp;bytes); </code></pre> <p>and couldn't do:</p> <pre><code>const int * ip; const char* s; size_t bytes; myAccessFunc(true, &amp;s, &amp;bytes); myAccessFunc(false, &amp;i, &amp;bytes); </code></pre> <p>I finally came around to:</p> <pre><code>const void* myAccessFunc(bool string, size_t* len); </code></pre> <p>and if the user does:</p> <pre><code>char* p = myAcccessFunc(true,&amp;bytes); </code></pre> <p>the compiler (GCC, at least), does complain about throwing away the qualifier.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload