自从我多年前意识到这一点,默认情况下这不会产生错误(至少在GCC中),我一直想知道为什么?
我知道您可以发出编译器标志来产生警告,但是它不应该总是出错吗?为什么非void函数没有返回值才有效?
评论中要求的示例:
#include <stdio.h>
int stringSize()
{
}
int main()
{
char cstring[5];
printf( "the last char is: %c\n", cstring[stringSize()-1] );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
...编译.
我现在正在学习C++,使用Bruce Eckel的"Thinking in C++",我在前面的章节中.我有一个C和Java背景.现在我遇到了以下问题:当我编译下面的源代码时
g++ A.cpp B.cpp bmain.cpp
Run Code Online (Sandbox Code Playgroud)
,程序输出"1"(正确)然后输出段错误.当我编译时
g++ -g A.cpp B.cpp bmain.cpp
Run Code Online (Sandbox Code Playgroud)
,完全相同的程序产生1和NO段错误!我必须说我发现这令人惊讶.有人能指出我做错了吗?我的操作系统是"Linux 2.6.35-30-generic#54-Ubuntu x86_64",我的g ++是版本"g ++(Ubuntu/Linaro 4.4.4-14ubuntu5)4.4.5".
编辑:只是因为这似乎是错误的重要来源,感谢@Evan Teran:B结构中的A构造函数永远不会被调用!我把"cout <<"写成了"<< endl;" 在里面,它不会打印任何东西
编辑:我现在在主要结尾处包含了"返回0",但这没有帮助.
啊:
#ifndef A_H
#define A_H
#include <string>
class A {
public:
int i;
std::string str;
void print();
A();
};
#endif
Run Code Online (Sandbox Code Playgroud)
A.cpp:
#include "A.h"
#include <iostream>
#include <string>
using namespace std;
void A::print() {
cout << str << " " << i << endl;
}
A::A() {
str = "initstr";
i = 0;
}
Run Code Online (Sandbox Code Playgroud)
BH: …
我在C中实现了一些基本的数据结构,我发现如果我从函数中省略了返回类型并调用该函数,则编译器不会生成错误.我编译cc file.c并没有使用-Wall(所以我错过了警告)但在其他编程语言中这是一个严重的错误,程序将无法编译.
根据Graham Borland的要求,这是一个简单的例子:
int test()
{
printf("Hi!");
}
int main()
{
test();
}
Run Code Online (Sandbox Code Playgroud) 考虑以下代码:
#include <iostream>
using namespace std;
int testReturn()
{
// no return
}
int main()
{
cout << "!!!Hello World!!!" << testReturn() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器警告:..\src\test.cpp:15:1: warning: no return statement in function returning non-void [-Wreturn-type].所以在我的编译器中,输出是1:
!!!Hello World!!!1
Run Code Online (Sandbox Code Playgroud)
没有将return语句指定为未指定的行为吗?还是总是不为零?我将非常感谢所有的帮助.