หากมีการแก้ไข Code บางส่วน แล้วเราต้องการที่จะเก็บ Code เก่าบางส่วนเอาไว้เพื่อเอาไว้อ้างอิง ในอนาคตในภาษา C ซึ่งมีอยู่หลายวิธี
หลายๆคนอาจจะใช้วิธีการ Block comment แต่การ Block comment นั้นมีข้อเสียตรงที่ หากใน Code ของเรามี Block comment อยู่ก็จะให้เกิด syntax error ได้ ตามตัวอย่างด้านล่างนี้
#include <stdio.h>
int main(void)
{
/* /* Month */
printf("This month is May\n");
printf("This month is Jul\n"); */
/* Day of week */
printf("This day is Monday\n");
return 0;
}
อีกวิธีหนึ่งก็คือการใช้ #ifdef NOT_DEFINE แล้วปิดด้วย #endif ก็สามารถทำได้เช่นกัน แต่ก็มีข้อเสียตรงที่ต้องระวังหากมีใครไปเปิดปิด ค่า Define ของเรา ก็จะทำให้ code ที่เราปิดไว้ทำงานขึ้นมาได้
จึงมีอีกวิธีหนึ่งก็คือการใช้ #if 0 แล้วปิดด้วย #endif ซึ่ง compiler จะ compile #if 0 ออกมาเป็น เท็จเสมอทำให้ code ที่เราปิดไว้ไม่ถูก compile นั้นเอง
ตัวอย่างการใช้ #if 0
#include <stdio.h>
int main(void)
{
#if 0
/* Month */
printf("This month is May\n");
printf("This month is Jul\n");
#endif
/* Day of week */
printf("This day is Monday\n");
return 0;
}
แต่ข้อเสียของ #if 0 ก็มี นั้นคือ ไม่สามารถใช้กับ code ที่เขียนไม่ถูกต้องได้ เช่น การเขียนภาษาอื่นที่ไม่ใช่ภาษา C หรือ การใส่เครื่องหมาย double quote(“) หรือ single quote (‘) ที่ไม่ครบ หรือการใช้ block comment ที่ไม่ครบ block ก็จะทำให้เวลาใช้ #if 0 แล้วทำให้ compile แล้ว error
ตัวอย่าง
Double quote(“) ไม่ครบ
#include <stdio.h>
int main(void)
{
#if 0
/* Month */
printf(This month is May\n");
printf("This month is Jul\n");
#endif
/* Day of week */
printf("This day is Monday\n");
return 0;
}
Block comment ไม่ได้ปิดท้าย
#include <stdio.h>
int main(void)
{
#if 0
/* Month
printf("This month is May\n");
printf("This month is Jul\n");
#endif
/* Day of week */
printf("This day is Monday\n");
return 0;
}
อีกวิธีก็คือการใช้ Line comment ข้อเสียของวิธีนี้ก็คือ ต้องใช้ความสามารถของ IDE หรือ Text editor ช่วยในการ comment ในกรณีที่ code มีหลายๆบรรทัด ซึ่งส่วนใหญ่จะมีฟังชั่นเหล่านี้อยู่แล้ว
Line comment short cut ใน Sublime Text ก็คือ (Ctrl + /)
Line comment short cut ใน Notepad++ ก็คือ (Ctrl + k)
ตัวอย่าง Line comment
#include <stdio.h>
int main(void)
{
// /* Month*/
// printf("This month is May\n");
// printf("This month is Jul\n");
/* Day of week */
printf("This day is Monday\n");
return 0;
}
ดังนั้นหากจะต้องการที่จะเก็บ Code เก่าบางส่วนเอาไว้เพื่อเอาไว้อ้างอิง ก็ขอแนะนำให้ใช้ Line comment หรือหันมาใช้พวก Version control ดีกว่า