Arrays a[count++]

Arrays a[count++]

本文关键字:count++ Arrays      更新时间:2023-10-16

我是C 的初学者,所以请忍受我。以下只是完整程序的一部分。

用户输入第一个数字(假设'3')时,它将转到if语句。然后,[count ]变成[1](如果我没有错,因为计数最初是0)。阵列元素A [1]因此存储了3个输入。如果是,则该程序不只是跳过[0]?

int readarray(int a[], int capacity) {
int count = 0; 
    int input; 
    do {
        cout << "Enter a number (-1 to stop):  "; 
        cin >> input; 
        if (input != -1) {
            a[count++] = input; 
        }
    } while (input != -1 && count << capacity); 
    return count; 

,因为 count++是帖子增量运算符。它在表达式中使用count的当前值,并增加count。它没有定义增量发生的方式或何时发生,因此在同一语句中使用count的任何其他用途可能会产生意外的结果。

该语句等同于写作

a[count] = input;
count = count + 1;

作为个人意见,我认为您绝不应该在表达式中使用前/邮政增量/减少操作员。它不会产生更有效的代码,它的可读性较低,并且往往会因一个错误而最终出现。

no,Postfix递增(x++)返回变量的 old 值。因此, a[count++]从0到1增量count,但使用0(count的旧值)作为索引。

顺便说一句,count << capacity看起来不对。您是说count < capacity

而不是[count ],如果(input!= -1){a [count] = input;计数 }。这样,将将值分配给当前数组索引开始时,将分配给[0],然后计数将增加到1。因此,下一个迭代将具有[1]。