I am currently working on a project to get into more advanced concepts of C. One of the concepts I want to learn about is const-correctness, so I decided to make my entire codebase abide by this idea.
Say we have a function like this:
/*
* Creates and displays a window.
*
* Returns non-zero on failure, 0 on success.
*/
extern int window_create(
_In_z_ char const *const pz_title, /* window title */
uint32_t width, /* width in pixels */
uint32_t height, /* height in pixels */
bool isvsync, /* Should VSync be enabled? */
/*
* Pointer to a pointer to a "window" structure
* that will receive the freshly-created window.
* Must not be NULL.
*/
_Outptr_ struct window **pps_window
);
A window will be created, and the pointer pointed to by pps_window
will then point to the newly-created window struct.
Now, should I enforce const-correctness on the window **
parameter as well? Like so:
struct window **const pps_window
The thing is, in my opinion, because the pointer to the pointer itself is passed-by-value anyway, wouldn't explicitly marking it as const be somewhat pointless because the caller does not have to care if the pointer-to-pointer copy on the stack gets modified, or would it still be good practice to add it nonetheless?
I don't know if this will help as I don't really understand your question...
C does things the C way. Ask yourself the question what will happen in the following code example:
#include <stdio.h>
void change_i(int*);
int main() {
const int i = 5;
const int const* pi = &i;
// doesn't compile as expected...
//i = 1;
//*pi = 1;
printf("i is: %d\n", i);
change_i(pi);
printf("i is: %d\n", i);
}
void change_i(int* i) {
*i = 6;
}
What output are we expecting? We would think that i remains 5 right? Though C does not really care... I like to see pointers and const pointers as data types as well, some might say I'm wrong, some will agree, and what happens whit C is that we do have some kind of notion of datatypes but since C is weakly typed everything is essentially the same type, being "a pile of bits". In this example, C casts the const pointer to a "normal" pointer in the function change_i. Here is the result:
i is: 5
i is: 6
That doesn't mean const is useless, what it does is say "I cannot change,". which does have an impact at compile time.., A way to implicitly avoid writing hacky code like I just showed would be trough, example give: typedefs:
typedef const int const* * const* my_special_integer_type;
my_special_integer_type i = ...;
void do_something(my_special_integer_type i) {
/*
* code...
*/
}
Just to give an idea, hope this helped...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.