I coded different functions and didn't find a standard that define crystal clear how many variables you can use (fields, local or as parameters of modifiers inside this function?

Do you know a cheatsheet with these limitations?



I'm not aware of any cheat sheet and the problem is that Solidity checks for local stack size in several different places during a function call but emits the same error message, so depending on how you combine function arguments, variables declared inside the function block and return values, the error message "Stack to deep, try removing local variables" sometimes appears and sometimes doesn't. e.g.:

      f (uint a, uint b, uint c, uint d, string e, string f, string g, string h) 
returns (uint, uint, uint, uint, string, string, string, string) { 

        return (a,b,c,d,e,f,g,h);

works, but:

      f (uint a, uint b, uint c, uint d, string e, string f, string g) 
returns (uint, uint, uint, uint, string, string, string, string, string) { 

        return (a,b,c,d,e,f,g,g,g);

produces: "CompilerError: Stack to deep, try removing local variables."

(In the second I have removed a function argument of type string and added it to the return values).

Even if you (for some reason) assume a return value of type 'string memory' takes two storage slots, the first example should not have worked either (8 input parameters + 4 single-slot-return values + 4 double-slot-return values = 20 stack slots). So I believe there is some work to be done in Solidity maybe?

But generally, from what I've read:

  • All function arguments take one slot
  • Any other variable declared inside the function or returned by the function takes one slot if it's in memory and two slots if it's a storage reference.

Together, you can't have more than 16.

As I mentioned before, there seem to be edge cases like the one above, but this generally works. I know this doesn't answer your question clearly, but I'm hoping someone else can clarify further!

EDIT: Assuming you're talking about local variables here, variables in storage don't have these limitation as the reason for max 16 local variables is a max stack size of 1024 slots - nothing to do with state variables.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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