C++:函数先定义后执行

  贼神奇的是,直到昨天在写flex规则的时候我才知道C++中的函数要么在使用之前先定义,要么将实现放在调用之前,不允许先调用后实现。之前一年多竟然不知道这件事,汗````,当然也是可能这件事本身和我思考方向是反着的,所以之前从来没有出现类似的问题。

  具体来说就是,这段代码会报错:

#include<iostream>
using namespace std;

int main(){
    halfpoint();
    return 0;
}
void halfpoint(){
    cout<<"hello"<<endl;
}

  而这段则不会

#include<iostream>
using namespace std;
void halfpoint(){
    cout<<"hello"<<endl;
}
int main(){
    halfpoint();
    return 0;
}

  解决的方法还有先声明:

#include<iostream>
using namespace std;
void halfpoint();
int main(){
    halfpoint();
    return 0;
}
void halfpoint(){
    cout<<"hello"<<endl;
}

这个问题在flex规则的编写时也有体现,比如下面的代码

{%
void yyerror(char *s);
%}
<comment><<EOF>>    {yyerror("EOF in comment");
yyterminate();}
%%
void yyerror(char *s){
printf("#%d ERROR \"%s\"\n",curr_lineno,&(*s));
return;}

当初一直好奇为什么必须先加一个对yyerror的定义,后来明白是因为在处理EOF错误时用到了这个函数,但是还没有实现。

猜你喜欢

转载自www.cnblogs.com/jiading/p/10799791.html