1) 下面代码的结果是什么?(台湾某cpu公司05年笔试题)
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
#include
<
iostream
>
using
namespace
std;

#define
product(x)(x*x)

int
main()

{
inti=3,j,k;
j=product(i++);
k=product(++i);
cout<<"j="<<j<<",k="<<k<<endl;
return0;
}

答案
#region答案
j=9,k=49,因为product(i++)=(i++*i++),所以j等于,此时i为,product(++i)要求先累加i,则i为,所以,k结果为
#endregion
2) 下面代码的结果是什么?(国内公司05年笔试题)
int
a
=
5
,b
=
3
;

!
a
&&
b
++
;
执行后
a
和
b
的值是
?
答案
#region答案
a为5,b为3,因为!a使表达式为假,则不必再去计算后面的了。
#endregion
3) 下面的代码两种写法,你认为哪种更好?(美国某嵌入式公司05年10月笔试题)
写法1:
写法2:
if
(a
==
'
A
'
)

{
a++;
}


答案
#region答案
第1种更好,因为如果不小心把“==”写成了“=”,则是对常量赋值,编译器会报错的,而第2种会通过编译。
#endregion

4) 下面代码的结果是什么?(台湾某cpu公司05年笔试题)
char
foo()

{
unsignedinta=6;
intb=-20;
charc;
(a+b>6)?(c=1):(c=0);
returnc;
}


答案
#region答案
返回值为1,因为unsignedint的数与int类型的数进行运算,后者会自动转化为unsignedint型,因此a+b的值大于6
#endregion
5) 如何不使用中间变量进行两个数的交换?
答案
#region答案
方法一:
a=a+b;
b=a-b;
a=a-b;
但这个方法缺点是:如果a,b两个数很大,a+b会超界

方法二:
a=a^b;
b=a^b;
a=a^b;
这里不用担心超界的问题
#endregion
6) 如何判断一段程序是由C编译器还是C++编译器编译的?(美国某网络公司05年笔试题)
答案
#region答案
#include<iostream>
usingnamespacestd;

intmain()


{
charch;
stringword;
#ifdef__cplusplus
cout<<"hello,c++"<<endl;
#endif
cin>>ch;
return0;
}


#include <stdio.h>
intmain()


{
#ifdef__STDC__
printf("hello,cprogram");
#endif
return0;
}


另外,再附加一些有用的常量定义
#include<iostream>
usingnamespacestd;

intmain()


{
charch;
stringword;
cout<<__FILE__<<":line"<<__LINE__<<endl;
cin>>ch;
return0;
}
__LINE__记录文件已经被编译的行数,__FILE__包含正在被编译的文件的名字
另外两个预定义名字分别包含当前被编译文件的编译时间__TIME__和日期
__DATE__时间格式为hh:mm:ss
#include<iostream>
usingnamespacestd;

intmain()


{
charch;
stringword;
cout<<__TIME__<<":"<<__DATE__<<endl;
cin>>ch;
return0;
}

#endregion