Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

c - Const on print of mutable object

Is it necessary to declare a mutable object const if the function does not modify it, or is this a redundancy that is not required? For example:

#include<stdio.h>

void print_num_ptr(const int *n) {
    printf("Example print: %d", *n);
}
int main(void) {
    int i=4;
    int *ptr_i=&i;
    print_num_ptr((const int*)ptr_i);
    (*ptr_i) ++;
    print_num_ptr((const int*)ptr_i);

}

Vs.

#include<stdio.h>

void print_num_ptr(int *n) {
    printf("Example print: %d", *n);
}
int main(void) {
    int i=4;
    int *ptr_i=&i;
    print_num_ptr(ptr_i);
    (*ptr_i) ++;
    print_num_ptr(ptr_i);
}

The first one just seems like a lot of headache unless there's a reason to use it over the first.

question from:https://stackoverflow.com/questions/66056049/const-on-print-of-mutable-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's a good habit to declare unchanging arguments as const both to advertise in the function signature that you will not change them, and to allow the compiler to optimize around that parameter.

Any function with a non-const argument implies it can or will modify that value, which if not true, communicates your intentions incorrectly.

Adding const to everything might seem like a useless ritual, but it has a very important function.

As a note, it's usually not necessary to cast to a const version of same. The compiler does that for you automatically. const acts as a safety that's implicitly applied, but won't be removed without going out of your way to break it off.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...