如果我们不从c ++中的非void返回类型函数返回任何东西,返回值是什么?[实验] [英] What is the return value if we dont return anything from a non void return typed function in c++?[Experimental]

查看:182
本文介绍了如果我们不从c ++中的非void返回类型函数返回任何东西,返回值是什么?[实验]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我观察到如果我不返回任何值从一个空函数与 int 返回类型是 1 。但在下面的例子中,它显示 4 3 2 为o / p(这是静态变量的值 si 打印在这里?如果我打印 si 我会得到o / p为2 3 4,与我现在得到的反向是有什么与函数的在这种情况下栈推和pop在这里?)。我还观察到,如果我使用float作为返回类型,然后它打印 nan nan nan 作为o / p。这是行为编译器依赖(我已经尝试过gcc和devcpp,观察相同)?这里实际上是什么?请分享您的想法。

I have observed that if I don’t return any value from an empty function with an int return type is 1. But in the below case it is showing 4 3 2 as o/p(is this the value of the static variable si getting printed here? if I print si I will get o/p as 2 3 4, in the reverse of what I get now. is there something to do with the function's stack push and pop here in this case?). Also I observed that if I use float as return type then it prints nan nan nan as o/p. Is this behavior compiler dependant (I have tried with both gcc and devcpp, observed the same)? What is actually going on here? Please share your thoughts on this.

#include<iostream>
using namespace std;


int f(int i){
     static int si = i;
     si = si + i;
     ///return si;
}

int main(){
    cout<<f(1)<<" "<<f(1)<<" "<<f(1);
    //cout<<" "<<f(1);    //if I uncomment this line then the o/p is: 4 3 2 5, it looks like it's printing the value of si.
}

看起来像 cout 导致反向打印静态变量 si 的值?

It looks like the behavior of cout causing the reverse printing of static variable si's value?

推荐答案

这是未定义的行为。你必须从非空函数 * 返回一些东西

It is undefined behaviour. You have to return something from a non-void function*

§6.6.3返回语句[stmt.return]


离开函数的结束相当于没有
值的返回;这会导致返回
函数中的未定义行为。

Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

* main()函数有一个隐式的 return 0 ,因此不需要显式返回。这是一种特殊情况。

* The main() function has an implicit return 0 so it is not necessary to explicitly return. This is a special case.

这篇关于如果我们不从c ++中的非void返回类型函数返回任何东西,返回值是什么?[实验]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆