在 C 語言編程中,初學者常遇到 error C2105: '++' needs l-value 錯誤。這通常發生在嘗試對非左值表達式進行自增操作時。
#include <stdio.h>
void main() {
FILE *fp;
int n[100];
int t = 0;
if ((fp = fopen("test.txt", "r")) == NULL) {
printf("失敗\n");
}
while (!feof(fp)) {
fscanf(fp, "%d", &n++); // 錯誤:n++ 不是左值
}
fclose(fp);
}
n++ 是後置自增運算,其結果是右值(臨時值),無法取地址。fscanf 的 %d 格式需要一個 int* 類型的參數,即變量的地址(左值)。
使用索引變量遍歷數組:
int i = 0;
while (!feof(fp)) {
fscanf(fp, "%d", &n[i++]);
}
feof(fp) 的使用時機,建議改用 fscanf(...) == 1 作為循環條件該錯誤的核心在於左值與右值的區別。只有可寫入的內存地址(變量、解引用指針、數組元素)才能作為左值。掌握這一概念能有效避免類似編譯錯誤。