且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

应返回类型没用类型限定符被使用,为了清楚?

更新时间:2023-09-17 23:37:40

这是通常的code,以尽可能准确地是怎么回事形容好。你得到这个警告,因为常量 const int的富(); 基本上是没有意义的。该API只是看起来,如果你不知道什么常量关键字手段更加清晰。不要超载的意思那样; 静态是够糟糕的,因为它是,而且也没有理由增加潜力较为混乱。

It's usually better for your code to describe as accurately as possible what's going on. You're getting this warning because the const in const int foo(); is basically meaningless. The API only seems clearer if you don't know what the const keyword means. Don't overload meaning like that; static is bad enough as it is, and there's no reason to add the potential for more confusion.

为const char * 指除 const int的不同的东西做,这就是为什么你的工具不抱怨它。前者是一个指向字符串常量,这意味着任何code调用该函数返回该类型不应该试图修改字符串的内容(这可能是在ROM为例)。在后一种情况下,系统没有办法强制执行,你不更改返回 INT ,所以预选赛是没有意义的。并行接近返回类型是:

const char * means something different than const int does, which is why your tool doesn't complain about it. The former is a pointer to a constant string, meaning any code calling the function returning that type shouldn't try to modify the contents of the string (it might be in ROM for example). In the latter case, the system has no way to enforce that you not make changes to the returned int, so the qualifier is meaningless. A closer parallel to the return types would be:

const int foo();
char * const foo2();

这都将导致您的静态分析给予警告 - 增加一个const修饰词来一回值是一个毫无意义的操作。它才有意义,当你有一个参考参数(或返回类型),比如你的为const char * 的例子。

其实,我只是做了一个小的测试程序,GCC甚至明确警告有关此问题:

In fact, I just made a little test program, and GCC even explicitly warns about this problem:

test.c:6: warning: type qualifiers ignored on function return type

所以它不是在抱怨只是你的静态分析程序。

So it's not just your static analysis program that's complaining.