Ryan
Ryan

Reputation: 14659

C: Is this a correct case for type-casting?

When I compile the following code (with -Wall), I get no warnings because I cast the *(str)++ to void type. However, if I do not cast that operation to void type, the follow warning is put: warning: value computed is not used [-Wunused-value] Is this the correct way to get rid of compiler warnings?

#include <stdio.h>

static void print(char *str)
{
  while(*str) {
    printf("%c\n", *str); 
    (void)*(str)++;
  }
}

int main(void)
{
  print("Hello");
  return 0;
}

Upvotes: 2

Views: 96

Answers (2)

Patrick Collins
Patrick Collins

Reputation: 10614

This is correct, but you're unnecessarily dereferencing -- you don't need *(str++), just str++. That aside, you probably just want

for(; *str; str++) { 
    printf("%c\n", *str);
}

Instead.

See also this question.

Upvotes: 2

quantdev
quantdev

Reputation: 23813

The correct way to get rid of those compilers warnings is to simply do str++;

Upvotes: 4

Related Questions