简体   繁体   English

C ++编译器未为未声明的变量引发错误

[英]C++ compiler not throwing error for undeclared variable

I tried to search for this specific problem and did not find anythying concrete. 我试图搜索此特定问题,但没有发现任何具体问题。

I was using an undeclared variable in my program and the compiler did not complain, it just gave a warning and the program runs fine. 我在程序中使用了一个未声明的变量,并且编译器没有抱怨,它只是发出了警告,程序运行正常。 My gcc version is 4.1.2 我的gcc版本是4.1.2

Below is a sample program I wrote to reproduce this, the variable "index" is not declared, why is the compiler treating "index" as a function and where does it find the definition of the function? 下面是我编写的用于重现此内容的示例程序,未声明变量“ 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;
 }

Compiling: 编译:

~ 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���

Running : 正在运行:

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

Looks like index is the name of a GCC builtin function: http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html 看起来index是GCC内置函数的名称: http : //gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html

So it is already declared, just not by you. 所以它已经被声明,只是不是您声明的。

The compiler is quite verbose about the situation. 编译器对此情况非常详细。 It things that index is an address of a function with signature 索引是带有签名的函数的地址

char *index(const char *s, int c);

See man index(3) . 参见man index(3) The corresponding header is somewhere in the chain of <iostream> 相应的标头位于<iostream>链中的某个位置

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

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