Mot so kien thc c s ve lap trnh bang ngon ng C

Phan trc | Muc luc | Phan sau

II. Chng trnh C au tien

Noi dung:

Vi phan nay ta lam quen vi cau truc cua mot chng trnh C va cac thanh phan cau tao nen no:

 

V du n gian chng trnh C

 
1: /* Chuong trinh dau tien */
2: #include <stdio.h>
3:
4: main()
5: {
6: printf ("Chao ban! Day la chuong trinh C dau tien cua toi.\n");
7: return 0;
8: }

Chu thch

Trong ngon ng C, hang chu thch c gii han gia hai dau /* va */. Trnh phien dch C se bo qua tat ca noi dung cha trong cap dau tren.

/* Chuong trinh dau tien */
 

oi vi C++, ta co the s dung // au moi hang chu thch.

/*
 This comment does not increase the size of
 the executable file (binary code), nor does
 it affect the performance speed.
*/

Tng ng vi:

// This comment does not increase the size of
// the executable file (binary code), nor does
// it affect the performance speed.

Chu y: Cac oan chu thch khong c phep long vao nhau.

Ch th #include

#include <stdio.h>

Ch th #include co tac dung bao bo tien x ly C tm tap tin ng vi noi dung <ten > va chep noi dung tap tin vao v tr cua include trong chng trnh. Cac tap ten ng vi noi dung trong < > thng la cac tap tin header ng vi nhng ham thong dung trong th vien cua C, thng nam trong th muc INCLUDE\. Neu cac tap header nam tai th muc lam viec, ta dung ngoac kep “ “ thay cho ngoac < >.

Chu y: Ngon ng C phan biet ch Hoa va ch thng !!!

Ham main()

Ham main() hang 4 la ham ac biet trong C. Moi chng trnh C phai co ham nay va chay chng trnh bat au t ham nay. Noi dung cac dong lenh trong ham nam gia ngoac { }.

Trong ham co lenh ac biet return co nhiem vu tra lai mot gia tr nao o cho ham. Mac nh no tra lai mot gia tr so nguyen (int). Hang 5 tra lai gia tr 0, ngha la chng trnh ket thuc bnh thng; neu gia tr tra lai khac 0, ieu o ngha la chng trnh ket thuc co loi.

Ham exit() , ham c s cua th vien C c nh ngha trong tap header stdlib.h (khi muon dung ham nay, phai goi #include <stdio.h>), dung e ket thuc chng trnh, nhng khong tra lai gia tr nao ca.

V du:
1: /* Chuong trinh dau tien */
2: #include <stdio.h>
3: #include <stdlib.h>
4: void main()
5: {
6: printf ("Chao ban! Day la chuong trinh C dau tien cua toi.\n");
7: exit(0);
8: }

Trong chng trnh tren, hang 4 co them t khoa void e xac nh kieu d lieu trong (empty). Neu void c them vao trc ten ham, ham se khong phai tra lai mot gia tr nao ca. Trong trng hp tren, v ham exit(0) khong tra gia tr, t void phai c them hang 4.

Bien dch va ket noi (compiling and linking)

Loi chng trnh va do sa loi (debugging)

Khi chng trnh nguon c dch va ket noi, co the xuat hien nhng loi cu phap, loi ket noi… ma ta can phai sa lai cho ung trc khi chng trnh c dch thanh dang thi hanh c (executable).

Cac chng trnh thng cung cap cho ngi s dung cong cu do sa loi (debugger). Sinh vien nen tap lam quen vi cong cu nay e nang cao hieu qua lap trnh.

Phan trc | Muc luc | Phan sau