📜  C++ 程序的输出 | 21套

📅  最后修改于: 2022-05-13 01:56:10.965000             🧑  作者: Mango

C++ 程序的输出 | 21套

这个程序的输出是什么?

#include
using namespace std;
int x; // Global x
  
int main()
{
    int x = 10; // Local x
    cout << "Value of global x is " << ::x << endl;
    cout << "Value of local x is " << x; 
    return 0;
}

输出:

Value of global x is 0
Value of local x is 10

在 C++ 中,可以使用作用域解析运算符(::) 访问全局变量(如果我们有一个同名的局部变量)。


这个程序的输出是什么?

#include 
using namespace std;
int a = 90;
  
int fun(int x, int *y = &a)
{
    *y = x + *y;
    return x + *y;
}
  
int main()
{
    int a = 5, b = 10;
  
    a = fun(a);
    cout << a << " " << b << endl;
  
    b = fun(::a,&a);
    cout << a << " " << b << endl;
  
    return 0;
}
100   10
195   290

有两个名为“a”的变量,一个是全局变量,另一个是局部变量。当我们调用a = fun(a); ,它调用 int fun(int x, int *y=&a),这里指向全局变量(即 a = 90)的指针被赋值给 y。所以。
*y = x + *y; // 变成 5 + 90
返回 x + *y; // 变成 5 + 95




这个程序的输出是什么?

#include 
using namespace std;
int a = 2;
  
int fun(int *a)
{
    ::a *= *a;
    cout << ::a << endl;
    return *a;
}
  
int main()
{
    int a = 9;
    int &x = ::a;
  
    ::a += fun(&x);
    cout << x;
}

输出:

4
8

每次使用 ::a 时,函数fun 都会访问全局变量。局部变量值不影响 a 的值。


这个程序的输出是什么?

#include 
using namespace std;
  
int main()
{
    char *A[] = { "abcx", "dbba", "cccc"};
    char var = *(A+1) - *A+1;
    cout << (*A + var);
}

输出:

bba

这里的数组表示是 A[0] = “abcx”, A[1] = “dbba”, A[2] = “cccc”。 (pointer)* >(binary) + 的优先级,以及 '*' 的执行顺序是从右到左。如果“A”地址是“x”,则“*(A+1)”的地址是“x+6”,“*A+1”的地址是“x+1”。所以var的整数值= 6(两点之间的字符总数(x + 6)-(x + 1)+ 1)。在打印期间,运算符'+' 现在重载,指针指向 'x+7' 。为此,程序的输出。这个程序的输出是什么?

#include 
using namespace std;
  
int main()
{
    char a = 'a', b = 'x';
    char c = (b ^ a >> 1 * 2) +(b && a >> 1 * 2 );
    cout << " c = " << c;
}

输出:

c = 97

a 的整数值 = 97 (01100001),b 的整数值 = 120 (01111000),'*' > '>>' > '^' > '&&' 的优先级。
所以表达式是' ((b ^ (a >> (1 * 2))) – (b && (a >> (1 * 2 )))))'。表达式的整数值
a >> 1 * 2 = 24 b ^ a >> 1 * 2 = 96 b && a >> 1 * 2 = 1 即 97。

这个程序的输出是什么?

#include 
using namespace std;
  
int main()
{
    int i = 5, j = 3;
    switch(j)
    {
    case 1:
        if (i < 10) cout << "\ncase 1";
        else if (i > 10)
           case 2:
               cout << "case 2";
        else if (i==10)
           case 3:
    default:
        cout << "case 3";
        cout << "hello";
    }
}

输出:

case 3hello

既然j=3满足条件,那么就进入case 3。case 3什么都没有,也没有break。所以默认执行。有关详细信息,请参阅 C 中的 switch 语句。