简体   繁体   中英

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

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.

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, eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM