简体   繁体   English

gcc / g ++警告,如果比较两个指针的地址而不是内容?

[英]gcc/g++ warning if comparing two pointers' addresses instead of contents?

Suppose I have a function with pointer inputs 假设我有一个带有指针输入的函数

void f(int *a, int *b) {
    if (*a < *b) {
        printf("hello!\n");
    }
}

where *a < *b is the correct behavior. *a < *b是正确的行为。

Is there a warning in gcc that I can turn on so whenever I write code such as gcc中是否有警告,我可以打开它,所以每当我编写诸如

a < b

when a , b are int * the compiler would warn me? abint *编译器会警告我吗?

There cannot be such warnings, because a < b where both a and b are pointers to int is a legitimate test that your code could do elsewhere. 不能有这样的警告,因为a < b其中两个ab是指向int 是一个合法的测试 ,你的代码可以做到万无一失。

A typical use case might be to represent a set of pointers by a sorted vector of pointers searched by dichotomy. 典型的用例可能是通过二分法搜索的指针的排序向量来表示一组指针。

You might consider customizing GCC with MELT by eg adding a #pragma to enable such a warning (in some selected places) but you'll need some time to implement the warning itself. 您可能考虑通过添加#pragma (在某些选定的地方)启用这样的警告(例如,在某些选定的位置)来使用MELT自定义GCC,但是您将需要一些时间来实现警告本身。 I'm not sure it is worth spending a week of your time to customize GCC this way. 我不确定是否值得花一个星期的时间来自定义GCC。

Technically, the C standard wants a and b to point inside the same aggregate (otherwise it is undefined behavior, or at least unspecified one), but on most systems you can compare any pointers of the same type. 从技术上讲,C标准希望ab指向相同的聚合(否则它是未定义的行为,或者至少是未指定的行为),但是在大多数系统上,您可以比较任何相同类型的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM