Understanding syntax



  • Hi,
    I have a question on the syntax used in the Soil Moisture sensor (solar powered version). I usually understand most of code, but I'm still lacking a lot of the detailed mechanisms of such powerful language.
    I read in the code:

    #define N_ELEMENTS(array) (sizeof(array)/sizeof((array)[0]))
    const int SENSOR_ANALOG_PINS[] = {A4, A5};
    

    then later on:

    for (int i = 0; i < N_ELEMENTS(SENSOR_ANALOG_PINS); i++) {
    

    I don't understand the sequence: how the Define statement can dimension the array N_Elements before the code defines the array itself ? Also I don't understand the formula in the define statement (a division? and the [0] ?)
    Could someone help me understand the detailed syntax and logic of that code ?

    And by the way, I saw in Arduino's website that they recommend not to use the #define statements (#define comments) . Do they recommend to avoid only due to "readibility"? Is there another way to code above statements without the #define ?

    Thanks,

    ricorico94



  • Hi @ricorico94 ,

    This is basic C syntax so I would recommend reading up on C language basics if you would like to have a better understanding.

    The #define macro here is a preprocessor macro. Any N_ELEMENTS(array) occurrences get replaced by (sizeof(array)/sizeof((array)[0])). array is a variable and gets replaced with the provided value.

    So in this case, the preprocessor will change

    N_ELEMENTS(SENSOR_ANALOG_PINS)
    

    to

    (sizeof(SENSOR_ANALOG_PINS)/sizeof((SENSOR_ANALOG_PINS)[0]))
    

    before compilation.

    So it will take the total byte size of the array (which is already defined at that point) divided by the byte size of the first element in the array, thus providing the number of elements in the array.

    Another way to code the statements without the #define would be to replace that part in the code yourself (like I did above).



  • Hi,

    Thanks a lot !
    This is precisely what I hadn't understood when reading various websites about arduino language and C language. Now I understand the difference between the #define and the definition of variables.
    So thanks again for this pragmatic explanations.

    br,
    ricorico94


Log in to reply
 

Suggested Topics

  • 1
  • 2
  • 3
  • 2
  • 198
  • 5

0
Online

11.2k
Users

11.1k
Topics

112.5k
Posts