如何在程序开始时声明

时间:2018-10-08 09:53:21

标签: c initialization global global-scope

在下面的清单中,尝试在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;
}

1 个答案:

答案 0 :(得分:1)

r.x = 150;

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

C不允许在全局级别进行分配。

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

#include <SDL2/SDL.h>

SDL_Rect r;

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

每个全局定义的变量均接受默认初始化:

  • integers变量设置为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.