1) 下面代码的结果是什么?(台湾某cpu公司05年笔试题)
using namespace std;
#define product(x) (x*x)
int main()
{
int i=3,j,k;
j = product(i++);
k = product(++i);
cout<<"j="<<j<<",k="<<k<<endl;
return 0;
}
答案#region 答案
j=9,k=49,因为product(i++)=(i++*i++),所以j等于,此时i为,product(++i) 要求先累加i,则i为,所以,k结果为
#endregion
2) 下面代码的结果是什么?(国内公司05年笔试题)
!a&&b++;
执行后a和b的值是?
a为 5,b为 3,因为!a使表达式为假,则不必再去计算后面的了。
#endregion
3) 下面的代码两种写法,你认为哪种更好?(美国某嵌入式公司05年10月笔试题)
写法1:
{
a++;
}
写法2:
{
a++;
}
答案#region 答案
第1种更好,因为如果不小心把“==”写成了“=”,则是对常量赋值,编译器会报错的,而第2种会通过编译。
#endregion
4) 下面代码的结果是什么?(台湾某cpu公司05年笔试题)
{
unsigned int a = 6;
int b = -20;
char c;
(a+b>6)?(c=1):(c=0);
return c;
}
答案#region 答案
返回值为1,因为unsigned int的数与int类型的数进行运算,后者会自动转化为unsigned int型,因此a+b的值大于6
#endregion
5) 如何不使用中间变量进行两个数的交换?
方法一:
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年笔试题)
#include <iostream>
using namespace std;
int main()
{
char ch;
string word;
#ifdef __cplusplus
cout<<"hello,c++"<<endl;
#endif
cin>>ch;
return 0;
}
#include <stdio.h>
int main()
{
#ifdef __STDC__
printf("hello,c program");
#endif
return 0;
}
另外,再附加一些有用的常量定义
#include <iostream>
using namespace std;
int main()
{
char ch;
string word;
cout <<__FILE__<< " : line " << __LINE__<<endl;
cin>>ch;
return 0;
}
__LINE__记录文件已经被编译的行数,__FILE__包含正在被编译的文件的名字
另外两个预定义名字分别包含当前被编译文件的编译时间__TIME__ 和日期
__DATE__ 时间格式为hh:mm:ss
#include <iostream>
using namespace std;
int main()
{
char ch;
string word;
cout <<__TIME__<< " : " << __DATE__<<endl;
cin>>ch;
return 0;
}
#endregion