2

I get the error assignment makes pointer from integer without a cast on the following code, what does it mean?

char * splitter;
if(splitter = strchr(key, ':') != NULL && *(splitter + 1) == ' ')
John
  • 3,238
  • 4
  • 22
  • 25
  • Related (not duplicate) http://stackoverflow.com/questions/3626905/why-does-this-c-program-print-weird-characters-in-output/3626912#3626912 – codaddict Sep 06 '10 at 02:44
  • For the sake of readability you should move the assignment out of the if statement. Also `*(splitter+1)` is equivalent to `splitter[1]`. – sellibitze Sep 06 '10 at 05:35

4 Answers4

3

It is because of the priority of operations. You need to put an extra set of parens to make sure it happens in the right order:

char * splitter;
if((splitter = strchr(key, ':')) != NULL && *(splitter + 1) == ' ')

otherwise the it will evaluate as this:

splitter = (strchr(key, ':') != NULL)

Since strchr(key, ':') != NULL will evaluate to either a 1 or a 0, in your example, you are assigning an integer to a pointer type, hence the warning.

however, i would just write it as in your second example, since it is simpler and less error prone. Making it one line shorter doesn't add anything except complexity.

Evan Teran
  • 87,561
  • 32
  • 179
  • 238
2

The not-equal operator != has higher precedence than the assignment operator =, so your original line reads like splitter = (strchr(key, ':') != NULL) rather than your intended (splitter = strchr(key, ':)) != NULL, so the compiler tries to assign to splitter the result of the comparison between strchr() and NULL.

Oblomov
  • 761
  • 3
  • 10
1

The != operator has a higher precedence than the = operator. That means your expression splitter = strchr(key, ':') != NULL is actually interpreted as splitter = (strchr(key, ':') != NULL).

Put the assignment into parentheses to increase the precedence of that part:

(splitter = strchr(key, ':')) != NULL
Gumbo
  • 643,351
  • 109
  • 780
  • 844
1

The != has higher precendence than the =. You should fully parenthesize:

if (((splitter = strchr(key, ':')) != NULL) && (*(splitter + 1) == ' '))
Carl Norum
  • 219,201
  • 40
  • 422
  • 469