Problem with macro

Asked

Viewed 30 times

1

I’m trying to solve the following exercise:

Write a program that defines and uses the PRINTARRAY macro to print an integer array. The macro should receive the array and the number of elements in the 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

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 the define

#define LEN_VETOR 4

Only "4--" is an invalid command, because it is 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.