Passing a bool as a param. C++

落爺英雄遲暮 提交于 2019-12-04 07:07:32

问题


what I am trying to do is an example below.

let's first define a bool.

bool cat = {false};

lets make a fake bool here.

bool setcat(bool booltoset)
{
 booltoset = true; 
 return booltoset;
}

now lets call it with cat.

printf("cat is %s", cat?"true":"false"); //set cat as false.

my question is; is it possible to actually pass a bool through an argument than set that bool?


回答1:


You need to pass by reference, i.e.:

void setcat(bool& booltoset)
{
 booltoset = true; 
}



回答2:


Any function argument is just a variable with scope identical to the function body. If it's an ordinary automatic variable, then changing it has not effect on the caller. This is sometimes useful: you can actually use the arguments, for example:

template<typename F>
void for_each(noexcept_it i, const noexcept_it end, const F &f) noexcept(noexcept(f))
{
   for(; i!=end; ++i) f(i);   // use i as iteration variable.
}

though the compiler will optimise such things anyway in most cases.



来源:https://stackoverflow.com/questions/18175280/passing-a-bool-as-a-param-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!