C ++返回值无返回语句 [英] C++ return value without return statement

查看:176
本文介绍了C ++返回值无返回语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行此程序时:

  #include< iostream> 

int sqr(int&);

int main()
{
int a = 5;
std :: cout<<(5)的平方为:< sqr(a)<< std :: endl;
std :: cout<<通过后,(a)是:< a<< std :: endl;
return 0;
}

int sqr(int& x)
{
x = x * x;
}

我有以下输出:

 (5)的平方为:2280716 
通过后,(a)为:25

什么是 2280716 ?并且,如何在函数中没有 return 语句,而是返回 sqr(a) int sqr(int& x)?



谢谢。

解决方案

严格来说,这会导致未定义的行为。在实践中,由于 sqr 有返回类型 int ,它总是返回一些东西,即使没有 return 语句。

添加 c>语句并在编译器中打开警告(例如 g ++ -Wall )。

  int sqr(int& x)
{
return x = x * x;
}


When I ran this program:

#include <iostream>

int sqr(int&);

int main()
{
    int a=5;
    std::cout<<"Square of (5) is: "<< sqr(a) <<std::endl;
    std::cout<<"After pass, (a) is: "<< a <<std::endl;
    return 0;
}

int sqr(int &x)
{
    x= x*x;
}

I got the following output:

Square of (5) is: 2280716
After pass, (a) is: 25

What is 2280716? And, how can I get a value returned to sqr(a) while there is no return statement in the function int sqr(int &x)?

Thanks.

解决方案

Strictly, this causes undefined behavior. In practice, since sqr has return type int, it will always return something, even if no return statement is present. That something can be any int value.

Add a return statement and turn on warnings in your compiler (g++ -Wall, for instance).

int sqr(int &x)
{
    return x = x*x;
}

这篇关于C ++返回值无返回语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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