如何在程序开始时声明

How to declare at beginning of program

在下面的清单中,尝试在调用 main() 函数之前声明矩形 "r" 会导致错误。

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

为什么必须在 main() 之后声明 "r"?

#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;
}
r.x = 150;

这不是声明,也不是定义,而是赋值。

C 不允许在全局级别赋值。

您仍然可以在全局范围内定义变量

#include <SDL2/SDL.h>

SDL_Rect r;

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

全局定义的每个变量都会进行默认初始化:

  • 整数变量设置为 0
  • 浮点变量设置为0.
  • 指针变量设置为NULL

甚至您还可以显式初始化它

#include <SDL2/SDL.h>

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

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

尽管初始化看起来类似于赋值,但实际上并不相同(正如您已经观察到的那样)。

More on the difference between assignment and initialisation here.