1

I've started learning solidity and have some simple questions:

  1. What is it that in contracts people write _varname, but not varname?

  2. In remix, I can execute inline functions like (function a() { b=4; } ) Why is this possible as the function isn't external or public?

  3. If instantiating a variable of type byte32 requires less gas than of type string, why do people use strings?

Thanks

1 Answer 1

4

Part 1:

Using an underscore before a variable name or varying case is used in many different programming languages to differentiate variables with underscores or alternate case from those that don't.

In Solidity, variables with underscores are often used to represent parameters. (I'm not sure how much programming experience you have, so forgive me if I sound pedantic)

Take the following example:

// The contract declaration.
pragma solidity ^0.4.14;

contract ExampleContract { 

    string myMessage;

    // The contract constructor
    function ExampleContract (string _myMessage) {
        // the value of myMessage is text
        // which is stored in the 'state' of the contract.
        // _myMessage is the parameter being passed in.
        // When you deploy the contract, you specify a value for _myMessage.
        // This value is then assigned to myMessage.
        myMessage = _myMessage;
    }

    // A "getter" function that just returns the value of myMessage,
    // which is stored in the contract's "state".
    function GetMessage () returns (string) {
        return myMessage;
    }
}

Part 2:

Functions are just ways to manipulate data. Given an input, produce an output.

Transactions are special types of functions that modify contract state. So if I had another function in the above contract for changing the message, calling that function with a new message would be considered a transaction.

But there's nothing wrong with using inline functions. Think about something like adding two numbers together within a function. int i = 1 + 1; is a valid operation in Solidity. Think of inline functions as just more complex operations.

Part 3.

Interesting observation. According to the Solidity docs:

As a rule of thumb, use bytes for arbitrary-length raw byte data and string for arbitrary-length string (UTF-8) data. If you can limit the length to a certain number of bytes, always use one of bytes1 to bytes32 because they are much cheaper.

Essentially, if you know the size of the string will never exceed 32 bytes, using bytes32 is perfectly valid. People use strings when they don't know what the maximum size should be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.