-1
#include <stdio.h>

struct point {
    int x;
    int y;
};

struct rectangle {
    struct point upper_left;
    struct point lower_right;
};

double calcul_area(struct rectangle a) {
    double width = a.lower_right.x - a.upper_left.x;
    double height = a.upper_left.y - a.lower_right.y;
    return width * height;
}

struct rectangle r;
r.upper_left.x = 3;
r.upper_left.y = 9;
r.lower_right.x = 12;
r.lower_right.y = 2;


int main() {
    printf("the size of rectangle is %f", calcul_area(r)); 
}

this code is for calculate the area of rectangle int the axis $x$,$y$.i don't want to talk about the idea of the code ,but just i want to understand why this error is shown.note that the code work fine when i make the above part of code under the main function,but when i put it before the main function i see the error

struct rectangle r;
r.upper_left.x = 3;
r.upper_left.y = 9;
r.lower_right.x = 12;
r.lower_right.y = 2;
Chris
  • 26,361
  • 5
  • 21
  • 42
  • 3
    All executable code has to be in a function. – pmacfarlane Mar 08 '23 at 13:09
  • C programming relies heavily on the concept of karma. If your code formatting is a complete mess, the universe will find ways to punish you for it with cryptic bugs and error messages. In more mundane terms usually referred to as the "s`**`t in, s`**`t out principle". – Lundin Mar 08 '23 at 15:07

1 Answers1

5

You cannot write code to execute in this way at global scope.

struct rectangle r;
r.upper_left.x=3;
r.upper_left.y=9;
r.lower_right.x=12;
r.lower_right.y=2;

Instead of this, you can write the initial values in this way (C99 or later):

struct rectangle r = {
    .upper_left = { .x = 3, .y = 9 },
    .lower_right = { .x = 12, .y = 2 }
};
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • but as it seem r.upper_left.x=3 and other is just like initialization of a variable,it's not an executable code –  Mar 08 '23 at 13:20
  • 1
    @anas take a look to [Initialization vs Assignment in C](https://stackoverflow.com/questions/35662831/initialization-vs-assignment-in-c) – David Ranieri Mar 08 '23 at 13:22
  • @anas No, that is not true. It is only initialization if you write it as in the second snippet of that answer. What you did was an assignment which is different. – Gerhardh Mar 08 '23 at 13:23