Shawn Karber
Shawn Karber

Reputation: 41

C is it possible to make a definition with struct variables?

I have a topic I'm trying to grasp with C, and that is definitions.

If I have a struct setup as:

struct grids {

   int x;
   int y;
   int endX;
   int endY;

};

and later I want to do perform an operation later such as:

 MAX(x,y)

with struct grids grid1 and grid2 as:

 MAX(grid1 -> x, grid2 -> x)

Is it possible to create a define like:

#define MAX(x,y)((x > y) ? x : y)

and have it use the fields from the structs?

Upvotes: 1

Views: 82

Answers (1)

lc2817
lc2817

Reputation: 3742

I am not sure that it is what you mean:

#include <stdio.h>
#define MAX(a) ((a.x > a.y) ? a.x : a.y)
#define MAX_X(a,b)((a.x > b.x) ? a.x : b.x)
#define MAX_Y(a,b)((a.y > b.y) ? a.y : b.y)

struct grids {
  int x;
  int y;
  int endX;
  int endY;
};

int main(void){
  struct grids a;
  a.x = 3;
  a.y = 4;
  struct grids b;
  b.x = 4;
  b.y = 3;
  printf("MAX(a): %d\n",MAX(a)); // prints 4
  printf("MAX_X(a,b): %d\n",MAX_X(a,b)); // prints 4
  printf("MAX_Y(a,b): %d\n",MAX_Y(a,b)); // prints 4   
}

And it prints 4.

Upvotes: 2

Related Questions