Martynas
Martynas

Reputation: 627

Return variable from function to an input variable

How to change variable by calling function?

Example

byte a;
...

void setBit(byte variable, byte n){
variable |= (1<<n);

}

...
setBit(a,2);

System.out.println(a); // expected output "2"

I could write a = setBit(a,2); but thats not what i need

As example from Arduino

#define bitRead(value, bit) (((value) >> (bit)) & 0x01)
#define bitSet(value, bit) ((value) |= (1UL << (bit)))
#define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
#define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit)) 

Upvotes: 0

Views: 46

Answers (2)

Joeblade
Joeblade

Reputation: 1743

The answer is, it cannot be done unless you make your own ByteWrapper which would allow modification of it's internals.

you cannot pass basic types by reference like in c++. This is a good thing in a lot of circumstances and a thing to be missed under some specialized circumstances.

Similar to what Venkatesh tried to suggest, but different in that it doesn't use the Byte (which is immutable afaik) object you can implement the ByteWrapper , but it won't auto-cast to byte basic type like Byte. you'll have to call byteWrapper.getByte();

public class ByteWrapper {
    private byte byteValue = 0;
    public ByteWrapper(byte b) {
        byteValue = b;
    }

    public byte getByte() { return b; }
    public void setByte(byte b) { byteValue = b; }
}

then you can use

void setBit(ByteWrapper bw, byte n){
    bw.setByte(byte.getByte() |= (1<<n));
}

However, +1'ing almas shaikh's answer as that's the way to go in this case. much simpler and therefor more elegant.

Upvotes: 0

SMA
SMA

Reputation: 37083

You could use return from your setter method like:

private byte setBit(byte variable, byte n){
     variable |= (1<<n);
     return variable;
}

And modify caller code as:

a = setBit(a, 2);

Upvotes: 2

Related Questions