How to define optional variables in a function

Say if I said:

void move(int x, int y, int z = 0){ .... }

Would that make Z optional?

Tagged:

Answers

  • no, but this would:

    void move(int x, int... y)
    {
    }
    

    but then y is an Array of at least one value. You could ignore the values beginning from the third position. That is the literal answer to the question in the title, but you probably just want to do this:

    void move(int x, int y)
    {
       move(x, y, 0);
    }
    
    void move(int x, int y, int z)
    {
    }
    

    This is called overloading: there are two move() methods but they have a different number of arguments so they are treated as different methods. The first move() method just calls the second with the z parameter equal to 0.

  • Answer ✓
    void move(int x, int y) {
      move(x, y, 0);
    }
    
    void move(int x, int y, int z) {
    }
    
  • edited January 2018

    very helpful

    flexible number of parameters...

    void setup() {
      size(222, 222); 
      testFunctionWithVariableNumbersOfParameters( 5 );
      testFunctionWithVariableNumbersOfParameters( 5, 8, 9 );
      testFunctionWithVariableNumbersOfParameters( 5, 8, 9, 17, 3, 9 );
    }
    
    void testFunctionWithVariableNumbersOfParameters(  float... n ) {
      printArray(n); 
      println ("----------------");
    }
    
Sign In or Register to comment.