我知道未初始化的局部变量是未定义的行为(UB),并且该值可能具有可能影响进一步操作的陷阱表示,但有时我想仅使用随机数进行可视化表示,并且不会在其他部分使用它们.例如,程序在视觉效果中设置具有随机颜色的东西,例如:
void updateEffect(){
for(int i=0;i<1000;i++){
int r;
int g;
int b;
star[i].setColor(r%255,g%255,b%255);
bool isVisible;
star[i].setVisible(isVisible);
}
}
Run Code Online (Sandbox Code Playgroud)
是不是比它快
void updateEffect(){
for(int i=0;i<1000;i++){
star[i].setColor(rand()%255,rand()%255,rand()%255);
star[i].setVisible(rand()%2==0?true:false);
}
}
Run Code Online (Sandbox Code Playgroud)
并且还比其他随机数发生器更快?
今天早上我在我的一个图书馆找到了这个:
static tvec4 Min(const tvec4& a, const tvec4& b, tvec4& out)
{
tvec3::Min(a,b,out);
out.w = min(a.w,b.w);
}
Run Code Online (Sandbox Code Playgroud)
我期望编译器错误,因为此方法不返回任何内容,并且返回类型不返回void.
想到的唯一两件事是
在调用此方法的唯一位置,不使用或存储返回值.(此方法应该是void- tvec4返回类型是复制和粘贴错误)
tvec4正在创建一个默认构造,这看起来有点不同,哦,C++中的其他所有东西.
我还没有找到解决这个问题的C++规范部分.参考文献(ha)表示赞赏.
更新
在某些情况下,这会在VS2012中生成错误.我没有缩小具体细节,但它仍然很有趣.
我用Google搜索,似乎无法找到这个简单问题的答案.
使用遗留代码库(最近移植到Linux,并慢慢更新到新的编译器),我看到了很多
int myfunction(...)
{
// no return...
}
Run Code Online (Sandbox Code Playgroud)
我知道函数的隐式返回TYPE是int,但是当没有指定返回时,隐式返回VALUE是什么.我已经测试过并且得到了0,但这只是用gcc.这个编译器是特定的还是标准定义为0?
编辑:12/2017调整接受的答案基于它引用更新版本的标准.
为什么下面的代码输出正确?int GGT没有return语句,但代码确实有用吗?没有设置全局变量.
#include <stdio.h>
#include <stdlib.h>
int GGT(int, int);
void main() {
int x1, x2;
printf("Bitte geben Sie zwei Zahlen ein: \n");
scanf("%d", &x1);
scanf("%d", &x2);
printf("GGT ist: %d\n", GGT(x1, x2));
system("Pause");
}
int GGT(int x1, int x2) {
while(x1 != x2) {
if(x1 > x2) {
/*return*/ x1 = x1 - x2;
}
else {
/*return*/ x2 = x2 - x1;
}
}
}
Run Code Online (Sandbox Code Playgroud) 我在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;
string test(string s)
{
string rv = "Hey Hello";
if(s=="")
return rv;
else
cout<<"Not returning"<<endl;
}
int main()
{
string ss = test("test");
cout<<ss<<endl;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码不应该返回任何值,并且可能打印垃圾,但它返回" Hey Hello ",即使在测试函数的末尾没有return语句.你能告诉我为什么它的表现如此吗?
c ×4
c++ ×3
c++11 ×2
function ×1
garbage ×1
legacy-code ×1
methods ×1
return-value ×1
string ×1