013231
V2EX  ›  C

为何这段程序编译时会出现"redefinition"错误?

  •  
  •   013231 · Jul 15, 2012 · 2257 views
    This topic created in 5050 days ago, the information mentioned may be changed or developed.

    按照我的理解, 就是声明了一个变量p, 类型void(*)(), 然后用&fun给它赋值, 为什么会出错呢?
    void(*p)() = &fun;
    这样在定义时直接赋值就不会出错.
    4 replies    1970-01-01 08:00:00 +08:00
    hehuozhao
        1
    hehuozhao  
       Jul 15, 2012
    我用VS2010跑了一下是正确的,如果你把void (*p)();和p = &fun;放在main()里面的话。
    013231
        2
    013231  
    OP
       Jul 15, 2012
    @hehuozhao 问题正出在这里. C语言中, 声明可以在全局作用域进行, 但赋值不行. 所以"void(*p)() = &fun;"成功, "void (*p)();p = &fun;"失败.
    xpfd
        4
    xpfd  
       Jul 16, 2012
    p = &fun; 赋值语句,只能放在函数体内。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5522 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 07:42 · PVG 15:42 · LAX 00:42 · JFK 03:42
    ♥ Do have faith in what you're doing.