繁体   English   中英

C ++定义预处理器

[英]C++ define preprocessor

我正在学习C ++,对,我们正在讨论预处理器,但是我试图解决一个测验中的一个问题,这个问题使我有些困惑。.在运行程序之前,我尝试自己动手..和我的输出是..

系统已启动...
2处的数据是:27 28 29 30
1处的数据是:23 24 25 26
数据为:19

我检查了Xcode中的程序,看看我的输出是否正确,但正确的输出是下一个输出:

系统已启动...
1处的数据是:0 0 0 19
0处的数据是:7 0 0 0
数据为:19 0 0 0

这是代码...

#include <iostream>

namespace test{
#define COMPILE_FAST
#define PRINT_SPLIT(v) std::cout << (int)*((char*)(v)) << ' ' << \
(int)*((char*)(v) + 1) << ' ' << (int)*((char*)(v) +2) << ' ' << \
(int)*((char*)(v) + 3) << std::endl

    typedef unsigned long long uint;
    namespace er{
        typedef unsigned int uint;
    }
    void debug(void* data, int size = 0){
        if(size==0){
            std::cout << "The data is: ";
            PRINT_SPLIT(data);
        } else {
             while(size--){
                std::cout << "Data at " << size << " is: ";
                char* a = (char*)data;
                PRINT_SPLIT((a + (4+size)));
            }
        }
    }
}// End of Test namespace...

int main(){
    test::uint a = 19;
    test::er::uint b[] = {256,7};
    std::cout << "System started..." << std::endl;
    test::debug(b,2);
    test::debug(&a);
    std::cout << "Test complete";
    return 0;
}

我最大的疑问或我实际上不理解的是此预处理器中发生的事情,因为显然我所做的事情完全错误...

#define PRINT_SPLIT(v) std::cout << (int)*((char*)(v)) << ' ' << \
(int)*((char*)(v) + 1) << ' ' << (int)*((char*)(v) +2) << ' ' << \
(int)*((char*)(v) + 3) << std::endl

如果有人可以这么友善并给我一个简短的解释,我将非常感激。

宏打印4个连续字节的值(以int为单位)。 它使您可以查看如何在内存中布置4字节的int。

内存内容按字节显示如下(base10):

0x22abf0:       0       1       0       0       7       0       0       0
0x22abf8:       19      0       0       0       0       0       0       0
  • 0 1 0 0是256,即b [0]
  • 7 0 0 0是7,即b [1]
  • 19 0 0 0 0 0 0 0是19,即

sizeof(a)sizeof(b[0])不同,因为uint有2种不同的typedef。 即, test:uinttest::er::uint

的地址a比的地址大b[]即使b的后宣布a ,因为堆栈在存储器中向下生长。

最后,我想说输出代表有缺陷的程序,因为输出更合理地是:

System started...
Data at 1 is: 7 0 0 0
Data at 0 is: 0 1 0 0
The data is: 19 0 0 0

要获得该输出,需要按以下步骤更改程序:

         while(size--){
            std::cout << "Data at " << size << " is: ";
            int* a = (int*)data;
            PRINT_SPLIT((a + (size)));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM