I wish to return a pointer to data from a function. The caller should not modify that data. I want the compiler to flag an error if the caller is assigning the return value to a non const pointer.
I know that it is possible to cast away const, but I want the caller to be forced to do that cast instead of just an implicit cast or warning. (or no warning!, as on the compiler I am using). I believe the answer to my question is that it is not possible. I think that there is no way to prevent caller code like this from compiling, and that if the user deferences the data (buf in my example) it will be undefined behaviour.
Please note I am asking if it is possible to do this in the c language itself, and if not, an explanation of why the standard prevents this. I am not looking for a way to make this specific example flag an error using some specific compiler command line.
#include "stdio.h"
const int* get_buf_2()
{
static int arr[10] = {1};
return arr;
}
void get_buf(const int ** buf)
{
static int arr[10] = {1};
*buf = arr;
}
int main(int argc, char const *argv[])
{
int *buf;
get_buf(&buf);
printf("%d %d\n", buf[0], buf[1]);
buf = get_buf_2();
printf("%d %d\n", buf[0], buf[1]);
const int cbuf[10];
buf = cbuf;
return 0;
}
This code produces 3 warnings with clang and gcc, each time the pointer buf is assigned from a pointer to const. The two different warnings:
warning: passing 'int **' to parameter of type 'const int **' discards
qualifiers in nested pointer types [-Wincompatible-pointer-types-discards-qualifiers]
warning: assigning to 'int *' from 'const int *' discards qualifiers
[-Wincompatible-pointer-types-discards-qualifiers]
Possibly related:
Why can't I convert 'char**' to a 'const char* const*' in C?
Return Pointer To Non-Modifiable Member Array C++ gcc warning