How to declare at beginning of program

2019-03-04 17:23发布

问题:

In the listing below, an attempt to declare the rectangle "r" before the main() function is called results in an error.

error: 'r' does not name a type r.x = 150;<br>

Why must "r" be declared after main()?

#include <SDL2/SDL.h>

int main (int argc, char** argv) {
    // Creat a rect at pos ( 50, 50 ) that's 50 pixels wide and 50 pixels high.
    SDL_Rect r;
    r.x = 150;
    r.y = 150;
    r.w = 200;
    r.h = 100;

    SDL_Window* window = NULL;
    window = SDL_CreateWindow   ("SDL2 rectangle", SDL_WINDOWPOS_UNDEFINED,
                                 SDL_WINDOWPOS_UNDEFINED,
                                 640,
                                 480,
                                 SDL_WINDOW_SHOWN
    );

    // Setup renderer
    SDL_Renderer* renderer = NULL;
    renderer =  SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED);
    SDL_SetRenderDrawColor( renderer, 0, 0, 0, 255 ); // black background
    SDL_RenderClear( renderer );    // Clear winow
    SDL_SetRenderDrawColor( renderer, 0, 255, 255, 255 ); // rgba drawing color

    // Render rect
    SDL_RenderFillRect( renderer, &r );

    // Render the rect to the screen
    SDL_RenderPresent(renderer);

    // Wait for 5 sec
    SDL_Delay( 5000 );

    SDL_DestroyWindow(window);
    SDL_Quit();

    return EXIT_SUCCESS;
}

回答1:

r.x = 150;

This is not a declaration, nor a definition, but an assignment.

C does not allow assignments on global level.

You still could define a variable at global scope

#include <SDL2/SDL.h>

SDL_Rect r;

int main (int argc, char** argv) {

Every variable defined globally undergoes a default initialisation:

  • integers variables are set to 0.
  • floating point variables are set to 0..
  • pointer variables are set to NULL.

Even more you could also initialise it explicitly

#include <SDL2/SDL.h>

SDL_Rect r = {1, 2, 3, 4};

int main (int argc, char** argv) {

Although an initialisation looks similar to an assignment it is not the same (as you already observed).

More on the difference between assignment and initialisation here.