走进C++程序世界-----函数相关(全局变量)

全局变量

在函数外面定义的变量的作用域为全局,在程序的任何函数中都可用。与全局变量同名的局部变量不会修改全局变量的值,但会隐藏它。如果函数中有一个与全局变量同 名的局部变量时,则在函数中使用该名称时,指得是局部变量而不是全局变量。这个也是面试中经常问到的?局部变量能否和全局变量重名?具体看下面的代码

#include <iostream>

int x = 5;
int y = 7;

void myfunction()
{
    using namespace std;

    int y = 10;
    cout << "********myfunction start******" << endl;
    cout << "myfunction x = " << x << endl;
    cout << "myfunction y = " << y << endl;
    cout << "********myfunction end******" << endl;

    return;
}
int main()
{
    using namespace std;
    cout << "执行函数myfunction 前:" << endl;
    cout << "main x = " << x << endl;
    cout << "main y = " << y << endl;

    myfunction();
    cout << "执行函数myfunction 后:" << endl;
    cout << "main x = " << x << endl;
    cout << "main y = " << y << endl;

    return 0;
}

输出:

行函数myfunction 前:
main x = 5
main y = 7
********myfunction start******
myfunction x = 5
myfunction y = 10
********myfunction end******
执行函数myfunction 后:
main x = 5
main y = 7

在C++中,全局变量是合法的,但人们几乎不使用它。在C语言中经常使用,但它很危险,因为不知道程序的哪些地方会修改它的数值。

******************************************************************华丽分界线*******************************************************

默认参数

long function(int x = 50);

该原型指出:函数function()接受一个int参数,并返回long型值,如果没有提供参数则使用默认值50.由于函数原型中可以不包含参数名,因此上面的生命也可以写成这样

long function( x = 50);

生命默认参数对函数定义没有影响,在上述函数的定义中,函数头如下:

long function( int x)
{
    xxxxxx;
}

如果调用该函数时没有提供参数,编译器将把X的设置成默认数值50.看下面的例子:

#include <iostream>
int area(int length,int width = 25, int height = 1);

int area(int length,int width,int height)
{
    return length*width*height;
}
int main()
{
    using namespace std;

    int length = 100;
    int width = 50;
    int height = 2;

    cout << "area(length,width,height) is :" << area(length,width,height) << endl;
    cout << "area(length,width) is :" << area(length,width) << endl;
    cout << "area(length) is :" << area(length) << endl;

    return 0;

}

输出:

area(length,width,height) is :10000
area(length,width) is :5000
area(length) is :2500

重载函数


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值