How to Pass a Reference to a Boolean Rather Than Its Value

How to pass a reference to a Boolean rather than its value?

I gave you partially wrong information the other day ( I was having a brain fart), and need to apologize for that. I had overlooked something in my testing...

Here is what you need if you don't want to make the RefBool instances as I suggested (requires more legwork, not recommended):

/// Mutates a boolean:
func toggle(_ boolean: inout Bool) -> Bool {
boolean ? (boolean = false) : (boolean = true)
return boolean
}

/// Static state manager for Booleans
struct IsOn {

private static var
_previewAudio = false,
_previewVisual = false,
_timerDisplal = false,
_quickStart = false

enum State { case toggle, get }

static func previewAudio(_ toggleVal: State = .get) -> Bool {
if toggleVal == .toggle { toggle(&_previewAudio) }; return _previewAudio
}

// ... others
}

Testing:

let referenceToPA = IsOn.previewAudio

print ( IsOn.previewAudio() ) // False (default pram works)
print ( referenceToPA(.get) ) // False (can't use default pram)

referenceToPA(.toggle)

print ( IsOn.previewAudio() ) // True
print ( referenceToPA(.get) ) // True

IsOn.previewAudio(.toggle)

print ( IsOn.previewAudio() ) // False
print ( referenceToPA(.get) ) // False



But honestly, it would be easier to just do the RefBool from my other answer, then you wouldn't need the enum or the functions:

/// Holds a boolean in .val:
final class RefBool { var val: Bool; init(_ boolean: Bool) { val = boolean } }

/// Static state manager for Booleans
struct IsOn {
static var
previewAudio = RefBool(false),
previewVisual = RefBool(false),
timerDisplal = RefBool(false),
quickStart = RefBool(false)
}

Convenience Funcs (not necessary):

/// Mutates a boolean:
func toggle(_ boolean: inout Bool) -> Bool {
boolean ? (boolean = false) : (boolean = true)
return boolean
}

/// Mutates .val:
func toggle(_ refBool: RefBool) -> Bool {
refBool.val ? (refBool.val = false) : (refBool.val = true)
return refBool.val
}

Testing2:

let refToPA = IsOn.previewAudio

refToPA.val = true

print(refToPA.val) // true
print(IsOn.previewAudio.val) // true

toggle(&refToPA.val)

print(refToPA.val) // false
print(IsOn.previewAudio.val) // false

toggle(refToPA) // Using our fancy second toggle

print(refToPA.val) // true
print(IsOn.previewAudio.val) // true

Pass boolean value by reference

Probably better to do:

@interface MyViewController()
@property (nonatomic) BOOL sendEmails;
@end

For the method call:

[self updateEmailPreference:&(self ->_sendEmails) button:self.noEmailsCheckBox];

With the method still:

- (void) updateEmailPreference : (BOOL *) b
button : (UIButton *) button
{
if (*b) {*b = NO;}
else {*b = YES;}

if (*b) {
[button setBackgroundImage:[UIImage imageNamed:@"checked_checkbox"] forState:UIControlStateNormal];
} else {
[button setBackgroundImage:[UIImage imageNamed:@"unchecked_checkbox"] forState:UIControlStateNormal];
}
}

(Do note that there can be confusion about the variable to use in the call statement. If it's a property you must use the ivar reference and not the dot-qualified property, and the ivar name must have the _ prefix or not depending on how your properties are declared. Or just use a local variable, and copy the property value into and out of that as required.)

pass bool variable by reference in function argument

In addNewNode, in your last two else if blocks, you're passing in &ifExist. But ifExist is a bool* already, should just pass in ifExist.

I'm not sure, but It's possible that the return statements only in the first if blocks is ok so long as those cover all possible base cases of your recursive function. [I was not thinking straight, the return statements are definitely necessary in all branches - I meant that setting ifExist to true is only required in the base cases...]

But yeah, the passing ifExist by reference (effectively now bool **) inside addNewNode is definitely not right.

EDIT: To clarify, in your outermost call to addNewNode where you have...

bool ifExist = false;
Tree->root = addNewNode(Tree->root, k, v, &ifExist);

...you do need to pass in by reference.
But inside addNewNode, your last two if else blocks should be

else if ((k == currentNode->key && v < currentNode->value) || k < currentNode->key)
{
currentNode->left = addNewNode(currentNode->left, k, v, ifExist);
currentNode->left->parent = currentNode;
}
else if ((k == currentNode->key && v > currentNode->value) || k > currentNode->key)
{
currentNode->right = addNewNode(currentNode->right, k, v, ifExist);
currentNode->right->parent = currentNode;
}

I would advise doing instead:

bool exists = false;
bool * ifExist = &exists;
Tree->root = addNewNode(Tree->root, k, v, ifExist);

That way, the way addNewNode arguments look is consistent everywhere... which will prevent future arcidents due to copy paste.

Python: how to pass a reference to a function

You can use a list to enclose the inout variable:

def func(container):
container[0] = True

container = [False]
func(container)
print container[0]

The call-by-value/call-by-reference misnomer is an old debate. Python's semantics are more accurately described by CLU's call-by-sharing. See Fredrik Lundh's write up of this for more detail:

  • Call By Object

Pass boolean argument by reference

The option that's closest to passing a pointer/reference into f would be to pass it a mutable object, like a list:

def f(ok=None):
if isinstance(ok, list):
ok.append(True)
return "hello"

def x():
ok = []
a = f(ok)
print(a, ok.pop())

But the better solution IMO would be to return a tuple, and refactor that behavior into a new function so that you're sharing code without disturbing the existing API:

def f_with_flag():
return "hello", True

def f():
return f_with_flag()[0]

def x():
a, ok = f_with_flag()
print(a, ok)

java Boolean value not changing in called method

First, there is a lot of misinformation about parameter passing in Java, like "objects are passed by reference, primitives are passed by value" which is not true. Everything is passed by value.

You're not passing an object by reference in Java, you're passing an object reference by value. Boolean b does not hold a Boolean object, it holds a reference (a pointer) to a Boolean object.

Here's a good article about it: http://javadude.com/articles/passbyvalue.htm

Second, Boolean (like the other wrapper objects and also String) are immutable objects. So with an immutable object, and as they are passed by value (better said, their references are passed by value), you cannot achieve what you desire. You'll need to have a mutable object instead, like @rob mentioned.

Or use MutableBoolean from Apache Commons Lang.

How to update a boolean variable in the function which is passing as a parameter

Try this:

void printbool(bool *a)
{
*a = TRUE;
}

In main, call function like this: printbool(&a);

How to change Bool value within a function in javascript?

Several problems there:

  1. 'false' is not false.

  2. Variables are passed by value in JavaScript. Always. So there is no connection whatsoever between the boolVar in setToFalse and the isOpen you're passing into it. setToFalse(isOpen) is processed like this:

    • The value of isOpen is determined

    • That value (completely disconnected from isOpen) is passed into setToFalse

  3. JavaScript has some interesting handling around primitive types: If you try to use them like object types (var a = 42; a.toFixed(2); for instance), the value gets promoted to a temporary object, that object is used, and then the object is discarded. So if obj is false, obj.anything = "whatever" ends up being a no-op, because the object that temporarily exists ends up getting released as soon as the line finishes.

You could do something like what you're doing by promoting isOpen to an object via new Boolean, but beware that it will then act like an object, not a boolean:

function modifyVar(obj, val) {

obj.valueOf = obj.toSource = obj.toString = function(){ return val; };

}

function setToFalse(boolVar) {

modifyVar(boolVar, false);

}

var isOpen = new Boolean(true); // An object

setToFalse(isOpen);

snippet.log('isOpen ' + isOpen);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->

<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>


Related Topics



Leave a reply



Submit