如何在程序开始时声明 [英] How to declare at beginning of program

查看:117
本文介绍了如何在程序开始时声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

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

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;
}

推荐答案

r.x = 150;

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

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

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

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变量设置为0.
  • 浮点变量设置为0..
  • 指针变量设置为NULL.
  • 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).

在此处详细了解赋值和初始化之间的区别.

这篇关于如何在程序开始时声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆