C++ 中邪

· · 科技·工程

const& 一点也不安全。

#include <iostream>
void fun(const int &x) {
    // x = 10; // CE. error: assignment of read-only reference 'x'
    // *&x = 10; // CE. error: assignment of read-only location '* & x'
    *((int*)nullptr + (&x - (int*)nullptr)) = 10;
}
int main() {
    int x = 5;
    std::cout << x << std::endl;
    fun(x);
    std::cout << x << std::endl;
    return 0;
}

输入任何数,负数也可以,输出 "...\n3\n5\n100\n",... 是你输入的数转 size_t(一般是 uint64_t 或者 uint32_t)

#include <bits/stdc++.h>
using namespace std;
int x = 5;
istream &XXX(cin >> x);
constexpr int fun() {
    int y = x;
    return y;
}
int main()
{
    int a[fun()];
    cout << sizeof(a) / sizeof(int) << endl;
    a[1] = 5;
    a[5] = 3;
    a[1000000000000ll] = 100;
    cout << a[5] << endl;
    cout << a[1] << endl;
    cout << a[1000000000000ll] << endl;
    return 0;
}