Các kiểu dữ liệu trong C

Kiểu dữ liệu trong C (Data Types in C)


  Dữ liệu (Data):
  • Là những mẩu tin được máy tính lưu trữ và xử lý hoặc truy suất theo yêu cầu của người dùng hoặc theo tiến trình hoạt động của máy. 
  • Dữ liệu được chứa trong bộ nhớ của máy tính với một số lượng ô nhớ nhất định, tính theo đơn vị Byte. 

Kiểu dữ liệu (Data type): được định nghĩa với hai điểm chính:
  • Một tập hợp các giá trị (miền giá trị) mà một biểu thức thuộc kiểu đó có thể nhận được
  • Trên đó xác định một số phép toán


Mỗi biến trong c được kết hợp với một kiểu dữ liệu. Mỗi kiểu dữ liệu yêu cầu một lượng bộ nhớ và có những thao tác riêng biệt có thể được thực hiện trên nó.
Một vài kiểu dữ liệu cơ bản như:



  • char: The most basic data type in C. It stores a single character and requires a single byte of memory in almost all compilers.
  • int: As the name suggests, an int variable is used to store an integer.
  • float: It is used to store decimal numbers (numbers with floating point value) with single precision.
  • double: It is used to store decimal numbers (numbers with floating point value) with double precision.


DATA TYPEMEMORY (BYTES)RANGEFORMAT SPECIFIER
short int2-32,768 to 32,767%hd
unsigned short int20 to 65,535%hu
unsigned int40 to 4,294,967,295%u
int4-2,147,483,648 to 2,147,483,647%d
long int4-2,147,483,648 to 2,147,483,647%ld
unsigned long int40 to 4,294,967,295%lu
long long int8-(2^63) to (2^63)-1%lld
unsigned long long int80 to 18,446,744,073,709,551,615%llu
signed char1-128 to 127%c
unsigned char10 to 255%c
float4%f
double8%lf
long double12%Lf
Có thể sử dụng toán tử sizeof() để kiểm tra kiểu của biến. Ví dụ như đoạn code dưới đây

#include <stdio.h>
int main()
{
    int a = 1;
    char b ='G';
    double c = 3.14;
    printf("Hello World!\n");
  
    //printing the variables defined above along with their sizes
    printf("Hello! I am a character. My value is %c and "
           "my size is %lu byte.\n", b,sizeof(char));
    //can use sizeof(b) above as well
  
    printf("Hello! I am an integer. My value is %d and "
           "my size is %lu  bytes.\n", a,sizeof(int));
    //can use sizeof(a) above as well
  
    printf("Hello! I am a double floating point variable."
           " My value is %lf and my size is %lu bytes.\n",c,sizeof(double));
    //can use sizeof(c) above as well
  
    printf("Bye! See you soon. :)\n");
  
    return 0;
}

No comments:

Powered by Blogger.