1

Estou tentando resolver o seguinte exercicio:

Escreva um programa que defina e use a macro PRINTARRAY para imprimir um array de inteiros. A macro deverá receber o array e o numero de elementos no array como argumento

O que fiz ate agora:

#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;
}

O erro que recebo ao tentar compilar:

error: lvalue required as decrement operand

1 Resposta 1

2

Quando você usa a macro assim

  PRINTARRAY(vetor, LEN_VETOR);

esta linha é substituida por

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

Estas linhas por sua vez são substituídas por

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

por causa do define

#define LEN_VETOR 4

Só que "4--" é um comando inválido, porque está tentando modificar o valor de uma constante!
A solução ? Usar a macro com uma variável em lugar da constante, como no exemplo abaixo.

#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;
}

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .