c ++在for循环中使用#define constant(意外输出)

时间:2017-10-07 17:04:07

标签: c++

#include <iostream>
#define f 5;

template <class n>
int* iota(n* ai, int len)
{
    for(int i= 0; i<len; i++)
    {
        ai[i] = f + i ;
    }

    return ai ;
}

int main()
{
    int arr5 [5] ;
    int *arr5_iota = iota(arr5, 5) ;
    for(int i=0; i<5; i++)
        std :: cout << arr5_iota[i] << ", " ;
    std :: cout << std :: endl ;
    return 0;
}
  

输出:5,5,5,5,5,!!!!!!!!!!   预期:5,6,7,8,9,

为什么输出与使用5而不是f?!

不同

1 个答案:

答案 0 :(得分:4)

问题是您使用带有分号的#define,而不应该使用分号。在C中,预处理程序语句不使用分号。

它进入#define定义。

因此ai[i] = f + i;变为ai[i] = 5; + i;

由于+i;是一个无效的有效语句,编译器甚至不会警告你。

使用#define f 5来解决此问题。

相关问题