C ++编译器不会为未声明的变量抛出错误

时间:2014-11-23 01:27:57

标签: c++ g++

我试图搜索这个特定的问题,并没有发现任何具体的问题。

我在我的程序中使用了一个未声明的变量,并且编译器没有抱怨,它只是发出警告并且程序运行正常。我的gcc版本是4.1.2

下面是我为了重现这个而编写的示例程序,未声明变量“index”,为什么编译器将“index”视为一个函数,它在哪里找到函数的定义?

#include <iostream>
using namespace std;

int testfunction()
{
     try {
         cout << "inside testfunction method\n";
         return 2;
     } catch(...) {
         cout << "caught exception" << index << endl;
     }
     return 1;
 }
 int main()
 {
     cout << "Testfunction return value : " << testfunction() << endl;
 }

编译:

~ g++ throwreturntest.cpp 
throwreturntest.cpp: In function ���int testfunction()���:
throwreturntest.cpp:11: warning: the address of ���char* index(const char*, int)���, will always evaluate as ���true���

跑步:

~  ./a.out 
inside testfunction method
Testfunction return value : 2

2 个答案:

答案 0 :(得分:1)

看起来index是GCC内置函数的名称: http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html

所以它已经宣布,而不是你。

答案 1 :(得分:1)

编译器对这种情况非常冗长。索引是具有签名

的函数的地址
char *index(const char *s, int c);

man index(3)。相应的标题位于<iostream>

链中的某个位置