Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

Short hand array notation ใน C/C++


ถ้ามีค่าซ้ำใน C ใช้ shorthand array notation กำหนด array นั้น

ตัวอย่าง:

ตัวอย่างโค้ด

#include <stdio.h> int main() { int array[10] = {[0 ... 3]7, [4 ... 5]6,[6 ... 9]2}; for (int i = 0; i < 10; i++) printf("%d ", array[i]); return 0; }

ผลลัพธ์

7 7 7 7 6 6 2 2 2 2

ในโปรแกรมนี้:

int array[10] = {[0 ... 3]7, [4 ... 5]6,[6 ... 9]2}

เทียบเท่า:

int array[10] = {7, 7, 7, 7, 6, 6, 2, 2, 2, 2}.

ถ้ามี gap ระหว่าง array จะเติม 0 เข้าไป

ใน C++ โปรแกรมข้างต้นให้ output เหมือนกันแต่มี warnings