Home > Net >  Why can't I get bool to work properly in Solidity Assembly function?
Why can't I get bool to work properly in Solidity Assembly function?

Time:11-26

I'm making an IsPrime function using Solidity Assembly code.

The function takes a number as parameter and returns true for prime, and false otherwise.

I've gotten my function to work, but I had to do a workaround outside of the assembly code.

See the code below:

// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.4.26;

contract PrimeNumber{

    function isPrimeNumber(uint num1) public view returns(bool) {
        
        uint result = 20;  // bool result = true;
        

        assembly{
    
            for {let i := 2} lt(i, num1) {i := add(i, 1)}{
                if eq(mod(num1, i), 0) {result := 10}  // result := false
            }
        
         

        }
        if(result == 10){
            return false;
        }
        return true;  // return result;
    }
}


So the function works, but I can't for the life of me, get it to work properly using only BOOL and assembly.

I had to add a normal if/else statement after the assembly because I could only get the result to work properly as a UINT type.

I've tried switch statements but I get the error "true and false are not valid literals"

See comments for what I want to do.

CodePudding user response:

Solidity assembly is not able to work with true and false literals until Solidity version 0.6. I haven't found any info about this in the docs - only validated by trying different versions.

You can bypass this limitation by using false-like value, e.g. 0.

pragma solidity ^0.4.26;

contract PrimeNumber{
    function isPrimeNumber(uint num1) public view returns(bool) {
        bool result = true;
        assembly{
            for {let i := 2} lt(i, num1) {i := add(i, 1)}{
                if eq(mod(num1, i), 0) {
                    result := 0
                }
            }
        }
        return result;
    }
}

Note: Latest version of Solidity (November 2022) is 0.8.17. So if your use case allows it, I'd recommend you to use the latest version as it contains bug fixes and security improvements.

  • Related