What does this code mean?

So my professor has given me some sample code for our project and we are suppose to basically finish the program. Anyway I came across this puzzling if statement and I can't figure out what it means. Apparrently it's checking to see
if the left side equals 0, but the left side is an assignment statement.

 
this->centers = (Center *)malloc(sizeof(Center) * this->nMetaballs)


So why would an assignment statement have a value? I'm confused.

1
2
3
4
5
if ((this->centers = (Center *)malloc(sizeof(Center) * this->nMetaballs)) == 0)
{
      fprintf(stderr, "ERROR: Allocate centers array.\n", filename);
      exit(0);      
}


This is nMetaballs.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#ifndef _NSMETABALLS
#define _NSMETABALLS

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

class Metaballs {

typedef struct {
  double cx, cy, cz;
} Center;

public:
  Metaballs():nMetaballs(0), centers(0){};
  Metaballs(const char *);
  ~Metaballs();

  unsigned int getnMetaballs() { return this->nMetaballs; }
  
protected:
  unsigned int nMetaballs;
  Center *centers;
  FILE *fp;
  
};

#endif
That's not really what's happening here, if malloc fails it returns "NULL" which would be zero. As for the rest of the code zero times anything is zero so the if statement would see zero IOW false and trigger this part of the code. Anything other then zero is seen as true in boolean operation.

EDIT: In this way we can combine an assignment and an evaluation in the same line of code, it's slightley annoying to read at first but just read some of the stuff on this forum for a while and you get used to it pretty quick.
Last edited on
Thanks. Does that mean he doesn't need the == 0?
He would, as putting == 0 on the end reverses the meaning of the statement.
1
2
3
4
5
6
if(func() == 0) {
    // func was 0
}
if(func()) {
    // func was non-zero
}
Last edited on
Thank you!
Topic archived. No new replies allowed.