If void() does not return a value, why do we use i

2019-01-21 15:25发布

void f() means that f returns nothing. If void returns nothing, then why we use it? What is the main purpose of void?

标签: c++ types void
11条回答
够拽才男人
2楼-- · 2019-01-21 15:42

probably to tell the compiler " you dont need to push and pop all cpu-registers!"

查看更多
等我变得足够好
3楼-- · 2019-01-21 15:44

Cause consider some situations where you may have to do some calculation on global variables and put results in global variable or you want to print something depending on arguments , etc.. In these situations you can use the method which dont return value.. i.e.. void

查看更多
对你真心纯属浪费
4楼-- · 2019-01-21 15:46

Because sometimes you dont need a return value. That's why we use it.

查看更多
萌系小妹纸
5楼-- · 2019-01-21 15:46

Here's an example function:

struct SVeryBigStruct
{
    // a lot of data here
};

SVeryBigStruct foo()
{
    SVeryBigStruct bar;
    // calculate something here

    return bar;
}

And now here's another function:

void foo2(SVeryBigStruct& bar) // or SVeryBigStruct* pBar
{
    bar.member1 = ...
    bar.member2 = ...
}

The second function is faster, it doesn't have to copy whole struct.

查看更多
我只想做你的唯一
6楼-- · 2019-01-21 15:55

If you didn't have void, how would you tell the compiler that a function doesn't return a value?

查看更多
Ridiculous、
7楼-- · 2019-01-21 15:57

Sometimes it can be used to print something, rather than to return it. See http://en.wikipedia.org/wiki/Mutator_method#C_example for examples

查看更多
登录 后发表回答