When I use width outside the draw ,I got strange problem

LYYLYY
edited April 2018 in Questions about Code

Capture When I change w to 200,Rectangle can normally appear in the center.I am very puzzled ):

Tagged:

Answers

  • You need to assign the value of w inside setup.

    Kf

  • Hi,kfrajer ,This is useless and it will lead to an error.I know that using w in draw can solve this problem. But I want to know the problem with the above code

  • edited April 2018 Answer ✓

    When your sketch starts running, setup() is not actually the first thing that happens.

    The first thing that happens is your global variables are created.

    In your code, your variable w is a global variable. Space for it is created, and then it is assigned a value. The value it gets assigned is width/2. What does that equal? Well, we'll get back to that.

    After your global variables are created, setup() gets to run. Hopefully the first line in setup() is a call to size(). This call to size takes the sketch's size values, and assigns them to width and height.

    Wait... What were the values of width and height before size() ran? They were ZERO! So what values did width/2 have when your assigned it to your variable w? Well because it happened before size(), width still had a value of zero, and so your w value got half of zero, which is also zero.

    This is why you should not rely on using the values of width and height when assigning values to global variables at the global level. These values are not fully setup yet, because they get set up by setup(), which happens AFTER global variables get their initial values.

    This is why you should do:

    int w; // Create global variable (but don't give it a value yet).
    
    void setup(){
      size(400,400); // This is what sets up the values of width and height!
      w = width / 2; // At this point width is 400, not zero, so w is 200.
    }
    
  • need to assign

    @TfGuy44 did a great work explaining this. I just gave you a very short answer/solution.

    Kf

  • Answer ✓

    That's a Common Question

    https://forum.processing.org/two/discussion/8087/what-are-setup-and-draw

    I'd advise reading all the common questions before going much further, could save you (and tfguy) a lot of time.

  • @TfGuy44 Thanks for your patient response, I fully understand the problem :)

Sign In or Register to comment.