没有初始化变量的C++

C++ Without initialization variable

本文关键字:C++ 变量 初始化      更新时间:2023-10-16

我从朋友那里遇到了一个问题。问题是在没有初始化变量的情况下,如何打印0到10?

我知道使用初始化进行循环打印的方法

 for(int i=0;i<=10;i++) {
     cout<<i;
 }

此处int i = 0已初始化。那么,在不初始化相关变量的情况下,如何打印0到10个值呢?有没有可能?

你的朋友应该学会更精确地指定他们的问题。

int i; // i is not initialized
i = 0; // i is assigned
for( ;i<=10;i++)
{
  cout<<i;
}

保持简单:

cout << "0" << "1" << "2" << "3" << "4" << "5" << "6" << "7" << "8" << "9" << "10";
cout << "012345678910";

运行时递归:

void myPrint(int x)
{ 
    cout << x;
    if ( x < 10 )
       myPrint( x+1 );
}
myPrint(0);

编译时递归:

template<int x> void foo()
{ 
    foo<x-1>(); 
    cout << x << 'n'; 
}
template<> void foo<0>() 
{ 
    cout << 0 << 'n'; 
}
foo<10>();

使用模板元编程可以实现最简单的解决方案:

template<> void f<0>() { cout << 0; }
template<int I> void f() { f<I-1>(); cout << I; }
f<10>();

或者只使用递归lambda函数。

function<void(int)> f = [&f] (int i) { i ? f(i-1) : (void)0; cout << i; };
f(10);
#include <iostream>
template<int N>
struct printer {
  printer() {
    std::cout << N << std::endl;
    printer<N+1>();
  }
};
template<>
struct printer<10> {
  printer() {
    std::cout << 10 << std::endl;
  }
};
int main()  
{
  printer<0>();
  return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
int printAndAdd(int total, int next)
{
    std::cout << total;
    return total + next;
}
int main()
{
    std::vector<int> elevenOnes(11, 1);
    std::accumulate(elevenOnes.begin(), elevenOnes.end(), 0, printAndAdd);
    return 1;
}

看ma,没有常量(除了"%u"字符串文字,但不算数!!

#include <cstdio> /* C code. C code run. Run code, run. */
/* umad? */
static unsigned long zero, ten, i;
int main(int argc, const char ** argv)
{
        /* setting ten to the right value... No initialization whatsoever! */
        ++ten;
        ten = ten << ten;
        ten = (ten << ten) + ten;
        /* then it's just a matter of printing out the values! */
        for (; i <= ten; ++i) {
                printf("%u", i);
        }
        /* As we all know, the Roman Empire (The unholy one, not the holy one,
           which wasn't holy, Roman, or an empire) fell since lacking any
           concept of zero, they couldn't indicate successful termination of
           their C programs. */
        return zero;
}

还有另一个使用XOR的解决方案-如果XOR本身有任何值,它将变为零。因此,解决方案可能是:

int i;
i ^= i; // this effectively sets i to zero
for (; i <= 10; i++) {
    cout << i;
}

malloc、递归、模板怎么样。或者使用直接访问(长)0x12ff7b=1;(长)0x12ff7b=(长)0x12ff7b+1;只要(long)0x12ff7b在可写存储器中。这真的是一个悬而未决的问题

其他一些答案似乎认为我们可以使用参数初始化(或赋值)。我认为这是作弊,但如果允许的话,我会提交这个更简单的版本:

void f(int n){
    for(; n <= 10; ++n)
         cout << n;
}
int main() {
    f(0);
}
int I=0;
while (I!=11) {
    cout<< I; I++;
}