首页 文章

当在C89模式下编译时,以下程序如何输出`C89`和在C99模式下编译时输出`C99`?

提问于
浏览
123

我从网上找到了这个C程序:

#include <stdio.h>

int main(){

    printf("C%d\n",(int)(90-(-4.5//**/
    -4.5)));

    return 0;
}

这个程序的有趣之处在于,当它在C89模式下编译和运行时,它会打印 C89 ,当它被编译并在C99模式下运行时,它会打印 C99 . 但我无法弄清楚这个程序是如何工作的 .

你能解释 printf 的第二个参数如何在上面的程序中起作用吗?

3 回答

  • 132

    C99允许 // 式的评论,C89没有 . 所以,要翻译:

    C99:

    printf("C%d\n",(int)(90-(-4.5     /*Some  comment stuff*/
                             -4.5)));
    // Outputs: 99
    

    C89:

    printf("C%d\n",(int)(90-(-4.5/      
                             -4.5)));
    /* so  we get 90-1 or 89 */
    
  • 25

    由于 // 注释仅存在于C99及更高版本的标准中,因此代码等效于以下内容:

    #include <stdio.h>
    
    int main (void)
    {
      int vers;
    
      #if   __STDC_VERSION__ >= 201112L
        vers = 99; // oops
      #elif __STDC_VERSION__ >= 199901L
        vers = 99;
      #else
        vers = 90;
      #endif
    
      printf("C%d", vers);
    
      return 0;
    }
    

    正确的代码是:

    #include <stdio.h>
    
    int main (void)
    {
      int vers;
    
      #if   __STDC_VERSION__ >= 201112L
        vers = 11;
      #elif __STDC_VERSION__ >= 199901L
        vers = 99;
      #else
        vers = 90;
      #endif
    
      printf("C%d", vers);
    
      return 0;
    }
    
  • 9

    自C99以来引入了评论 // . 因此,您的代码在C89中与此相同

    #include <stdio.h>
    
    int main(){
    
        printf("C%d\n",(int)(90-(-4.5/
    -4.5)));
    
        return 0;
    }
    /* 90 - (-4.5 / -4.5) = 89 */
    

    在C99中等于这个

    #include <stdio.h>
    
    int main(){
    
        printf("C%d\n",(int)(90-(-4.5
    -4.5)));
    
        return 0;
    }
    /* 90 - (-4.5 - 4.5) = 99*/
    

相关问题