Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
724 B

9 years ago
  1. #include <stdio.h>
  2. #include <math.h>
  3. typedef struct point {
  4. double x, y;
  5. } point;
  6. /*
  7. Nested the anonymous struct in anonymous union together with a named struct
  8. to support direct access to 2D point in the 3D point structure.
  9. */
  10. typedef struct {
  11. union {
  12. struct point;
  13. point p2;
  14. };
  15. double z;
  16. } threepoint;
  17. double length(point p) {
  18. return sqrt(p.x * p.x + p.y * p.y);
  19. }
  20. double threelength(threepoint p) {
  21. return sqrt(p.x * p.x + p.y * p.y + p.z * p.z);
  22. }
  23. int main() {
  24. threepoint p = {.x = 3, .y = 0, .z = 4};
  25. printf("p is %g units from the origin\n", threelength(p));
  26. double xylength = length(p.p2);
  27. printf("Its projection onto the XY plane is %g units from the origin\n", xylength);
  28. }