Operations on struct variables in C

C++Server Side ProgrammingProgramming

Here we will see what type of operations can be performed on struct variables. Here basically one operation can be performed for struct. The operation is assignment operation. Some other operations like equality check or other are not available for stack.

Example

#include <stdio.h>
typedef struct { //define a structure for complex objects
   int real, imag;
}complex;
void displayComplex(complex c){
   printf("(%d + %di)\n", c.real, c.imag);
}
main() {
   complex c1 = {5, 2};
   complex c2 = {8, 6};
   printf("Complex numbers are:\n");
   displayComplex(c1);
   displayComplex(c2);
}

Output

Complex numbers are:
(5 + 2i)
(8 + 6i)

This works fine as we have assigned some values into struct. Now if we want to compare two struct objects, let us see the difference.

Example

#include <stdio.h>
typedef struct { //define a structure for complex objects
   int real, imag;
}complex;
void displayComplex(complex c){
   printf("(%d + %di)\n", c.real, c.imag);
}
main() {
   complex c1 = {5, 2};
   complex c2 = c1;
   printf("Complex numbers are:\n");
   displayComplex(c1);
   displayComplex(c2);
   if(c1 == c2){
      printf("Complex numbers are same.");
   } else {
      printf("Complex numbers are not same.");
   }
}

Output

[Error] invalid operands to binary == (have 'complex' and 'complex')
raja
Published on 30-Apr-2019 16:22:54
Advertisements