面试中你不可回避的C、C++的问题(二)

1.如何将a,b的值进行交换,并且不适用任何中间变量

#include <stdio.h>

void first(int a,int b)
{
    a=a+b;
    b=a-b;
    a=a-b;
    printf("%d %d\n",a,b);
}

void second(int a,int b)
{
    a=a^b;
    b=a^b;
    a=a^b;
    printf("%d %d\n",a,b);
}

int main()
{
    int a=10,b=1000;
    printf("%d %d\n",a,b);
    first(a,b);
    second(a,b);
    return 0;
}

2.使用预处理指令#define声明一个常数,用来表示一年中大约有多少秒?

#define SECOND_PER_YEAR (60*60*24*365)UL
3.写一个标准的宏MIN,这个宏输入两个参数并返回较小的一个

#define MIN(a,b) ((a)<=(b)?(a):(b))

4.Const的要求

       a)定义常量

       b)修饰函数的参数和返回值,甚至定义函数体

       c)在C语言中它总是要占用内存的,而且它的名字是全局符。C编译器不能把const看成一个编译期间的常量

       d)C语言默认const修饰的变量时外部链接,但是C++默认的是内部链接

例子:

/*使用的是main.cpp文件,并且是用mingw的编译器,编译没有问题*/
const int bufsize=100;
char buf[bufsize];
/*使用的是main.c文件,并且是用mingw的编译器,编译有问题*/
const int bufsize=100;
char buf[bufsize];
错误信息

error: variably modified 'buf' at file scope   char buf[bufsize];

5.Const与define的不同

         a)Const常量有数据类型,而宏常量没有数据类型。编译器可以对前者进行安全检查,而对后者只是进行简单的字符替换,

             没有安全检查,并且在字符串替换中可能产生意料不到的错误(边际效应)

         b)有些编译器对const常量可以进行调试,但是不能对宏常量进行调试

6.sizeof的基本要求--计算数据空间的字节数

#include <iostream>
#include <string>

using namespace std;

struct s1
{
    char a;
    double b;
    int c;
    char d;
};

struct s2
{
    char a;
    char b;
    int c;
    double d;
};

void basic()
{
    cout << sizeof(char) << endl;//1
    cout << sizeof(short) << endl;//2
    cout << sizeof(int) << endl;//4
    cout << sizeof(float) << endl;//4
    cout << sizeof(double) << endl;//8
    cout << sizeof(long) << endl;//4
    cout << sizeof(string) << endl;//4
}

int main()
{
    basic();
    //编译器会按照结构体中最大的一个类型对数据进行对齐
    cout<<sizeof(s1)<<endl;//24
    cout<<sizeof(s2)<<endl;//16
    return 0;
}
但是也有问题:

#include <iostream>
#include <string>

using namespace std;

struct s1
{
char a[8];
};

struct s2
{
double d;
};

struct s3
{
s1 s;
char a;
};

struct s4
{
s2 s;
char a;
};

void basic()
{
    cout << sizeof(char) << endl;//1
    cout << sizeof(short) << endl;//2
    cout << sizeof(int) << endl;//4
    cout << sizeof(float) << endl;//4
    cout << sizeof(double) << endl;//8
    cout << sizeof(long) << endl;//4
    cout << sizeof(string) << endl;//4
}

int main()
{
    basic();
    //在自己定义结构体的时候,如果空间紧张的话,最好考虑对齐因素来排列结构体里的元素
    cout<<sizeof(s1)<<endl; // 8
    cout<<sizeof(s2)<<endl; // 8
    cout<<sizeof(s3)<<endl; // 9
    cout<<sizeof(s4)<<endl; // 16;
    return 0;
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值