Spi*_*rix 125 c printf comments c99 c89
我从网上找到了这个C程序:
#include <stdio.h>
int main(){
printf("C%d\n",(int)(90-(-4.5//**/
-4.5)));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个程序的有趣之处在于,当它在C89模式下编译和运行时,它会打印C89
,当它被编译并在C99模式下运行时,它会打印出来C99
.但我无法弄清楚这个程序是如何工作的.
你能解释一下第二个参数如何printf
在上面的程序中起作用吗?
Pau*_*bel 132
C99允许//
风格的评论,C89没有.所以,要翻译:
C99:
printf("C%d\n",(int)(90-(-4.5 /*Some comment stuff*/
-4.5)));
// Outputs: 99
Run Code Online (Sandbox Code Playgroud)
C89:
printf("C%d\n",(int)(90-(-4.5/
-4.5)));
/* so we get 90-1 or 89 */
Run Code Online (Sandbox Code Playgroud)
ikh*_*ikh 25
//
自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 */
Run Code Online (Sandbox Code Playgroud)
在C99中等于这个
#include <stdio.h>
int main(){
printf("C%d\n",(int)(90-(-4.5
-4.5)));
return 0;
}
/* 90 - (-4.5 - 4.5) = 99*/
Run Code Online (Sandbox Code Playgroud)
由于//
注释仅存在于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;
}
Run Code Online (Sandbox Code Playgroud)
正确的代码是:
#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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5605 次 |
最近记录: |