Problem with macro

1

I'm trying to solve the following exercise:

  

Type a program that defines and uses the PRINTARRAY macro to print   an array of integers. The macro should receive the array and the number of   elements in array as argument

What I've done so far:

#include <stdio.h>
#include <stdlib.h>

#define LEN_VETOR 4
#define PRINTARRAY(vetor,length)while(length > 0){ \
                         printf("%d",vetor[length]);\
                         length--;                 \
                       }                           \

int main(void)
{
    int vetor[] = {1,2,3,4};
    PRINTARRAY(vetor,LEN_VETOR);
    return 0;
}

The error I get when trying to compile:

  

error: lvalue required as decrement operand

    
asked by anonymous 22.10.2018 / 00:59

1 answer

2

When you use the macro like this

  PRINTARRAY(vetor, LEN_VETOR);

This line is replaced by

while (LEN_VETOR > 0) {
  printf("%d",vetor[LEN_VETOR]);
  LEN_VETOR--;
}

These lines in turn are replaced by

while (4 > 0) {
  printf("%d",vetor[4]);
  4--; /* ****** PROBLEMA */
}

because of define

#define LEN_VETOR 4

Only "4--" is an invalid command because you are trying to modify the value of a constant!
The solution ? Use the macro with a variable instead of the constant, as in the example below.

#include <stdio.h>
#include <stdlib.h>

#define PRINTARRAY(vetor,length) while (length > 0) { \
  printf("%d",vetor[length-1]); /* atencao aqui para o -1 */ \
  length--; \
  }

int main(void)
{
  int vetor[] = { 1, 2, 3, 4 };
  int lenVetor = LEN_VETOR.
  PRINTARRAY(vetor, lenVetor);
  return 0;
}
    
22.10.2018 / 01:17