We have two pieces of code,which one do you prefer, and tell why.
A:
// a is a variable.
写法1:
if('A'==a) { a++; }
写法2:
if(a=='A') { a++; }
B:
写法1:
for(i=0;i<8;i++) { x=i+Y+J*7; printf("%d",x); }
写法2:
S=Y+J*7; for(i=0;i<8;i++) { printf("%d",i+S); }
解析:对于A代码段,我更偏向于喜欢写法1.因为在if判定条件中,他把常量写在前面,这样能有效防止由于大意把"=="写"="而造成的难以发现的错误。因为如果写成"="时,相当于给常量赋值,不会通过编译。
对于B代码段。我更喜欢写法2.因为在写法1中,他把x=i+Y+J*7.这样相对来说,复杂的计算写在了循环体内,相对于写法2,在效率上大大降低。
2.下面程序的结果是什么?
#inlcude <iostream> #include <stdio.h> #include <string.h> #include <conio.h> using namespace std; int main() { float a=1.0f; cout<<(int)a<<endl; cout<<&a<<endl; cout<<boolalpha<<((int)a == (int&)a) <<endl; float b=0.0f; cout<<(int)b<<endl; cout<<&b<<endl; cout<<(int&)b<<endl; cout<<boolalpha<<((int)b == (int&)b) <<endl; return 0; }
解析:
1;
输出变量a的地址;
输出浮点数a地址开始的sizeof(int)个字节当成int型数据输出。
false;
0;
变量b在内存中的地址;
0;
true;