#include <stdio.h> int main() { printf("Hello, World!\n"); return 0; }
在 C 语言中,变量用于存储可在程序中操作的数据。这是有关在 C:
中创建和使用变量的综合指南声明:
type variable_name;
示例:
int number; char letter; float salary;
初始化:
variable_name = value;
示例:
number = 10; letter = 'A'; salary = 50000.0;
声明和初始化组合:
type variable_name = value;
示例:
int age = 25; double pi = 3.14159; char grade = 'A';
示例:
int age; char _grade; float salary_2024;
变量的作用域是程序中可以访问该变量的部分。 C 中的变量可以是:
局部变量:在函数或块内声明,并且只能在该函数或块内访问。
void myFunction() { int localVar = 5; printf("%d", localVar); }
全局变量:在所有函数之外声明,并可从程序内的任何函数访问。
int globalVar = 10; void myFunction() { printf("%d", globalVar); } int main() { myFunction(); // Outputs: 10 return 0; }
常量是指一旦赋值就无法更改其值的变量。它们是使用 const 关键字声明的。
示例:
const int DAYS_IN_WEEK = 7; const float PI = 3.14159;
在 C 中,未初始化的局部变量包含垃圾值,而全局变量和静态变量默认初始化为零。
示例:
#include <stdio.h> int globalVar; // default value 0 int main() { int localVar; // contains garbage value printf("Global Variable: %d\n", globalVar); printf("Local Variable: %d\n", localVar); return 0; }
您可以在一行中声明多个相同类型的变量,并用逗号分隔它们。您也可以在声明时或稍后初始化它们。
示例:
// Declaring multiple variables without values int a, b, c; // Declaring and initializing some variables int x = 10, y, z = 30;
您可以通过链接赋值运算符将相同的值分配给多个变量。
示例:
int m, n, o; m = n = o = 50;
C 中的注释是不可执行的语句,用于描述和解释代码。它们对于使代码更具可读性和可维护性至关重要。 C 支持两种类型的注释:
单行注释以两个正斜杠 (//) 开头。该行 // 后面的所有内容都被视为注释。
语法:
// This is a single-line comment int x = 10; // x is initialized to 10
多行注释以/*开始,以*/结束。 /* 和 */ 之间的所有内容都被视为注释,无论它跨越多少行。
语法:
/* This is a multi-line comment. It can span multiple lines. */ int y = 20; /* y is initialized to 20 */
单行注释示例:
#include <stdio.h> int main() { // Print Hello, World! printf("Hello, World!\n"); // This prints the string to the console return 0; }
多行注释示例:
#include <stdio.h> int main() { /* This is a simple C program that prints Hello, World! to the console. */ printf("Hello, World!\n"); return 0; }
这些示例说明了如何在 C 语言中使用单行和多行注释来使代码更具可读性和可维护性。
在C中,输入和输出操作是使用标准库函数执行的。基本输入和输出最常用的函数是 printf 和 scanf。
printf 函数用于将文本和变量打印到控制台。
语法:
printf("format string", variable1, variable2, ...);
格式说明符:
示例:
#include <stdio.h> int main() { int age = 25; float salary = 50000.0; double pi = 3.141592653589793; char grade = 'A'; char name[] = "John"; printf("Age: %d\n", age); printf("Salary: %.2f\n", salary); printf("Pi: %.15lf\n", pi); printf("Grade: %c\n", grade); printf("Name: %s\n", name); return 0; }
scanf 函数用于从控制台读取格式化输入。
语法:
scanf("format string", &variable1, &variable2, ...);
示例:
#include <stdio.h> int main() { int age; float salary; double pi; char grade; char name[50]; printf("Enter age: "); scanf("%d", &age); printf("Enter salary: "); scanf("%f", &salary); printf("Enter pi value: "); scanf("%lf", &pi); printf("Enter grade: "); scanf(" %c", &grade); // Note the space before %c to consume any leftover newline character printf("Enter name: "); scanf("%s", name); // Reads a single word, stops at whitespace printf("\nYou entered:\n"); printf("Age: %d\n", age); printf("Salary: %.2f\n", salary); printf("Pi: %.15lf\n", pi); printf("Grade: %c\n", grade); printf("Name: %s\n", name); return 0; }
使用 fgets 读取一行文本:
语法:
fgets(buffer, size, stdin);
示例:
#include <stdio.h> int main() { char name[50]; printf("Enter your full name: "); fgets(name, sizeof(name), stdin); // Reads a line of text including spaces printf("Your name is: %s", name); return 0; }
getchar 示例:
#include <stdio.h> int main() { char ch; printf("Enter a character: "); ch = getchar(); printf("You entered: "); putchar(ch); printf("\n"); return 0; }
putchar Example:
#include <stdio.h> int main() { char ch = 'A'; printf("The character is: "); putchar(ch); printf("\n"); return 0; }
In C programming, data types specify the type of data that variables can store. C supports several basic and derived data types, each with specific properties. Here's a comprehensive guide to data types in C:
Example:
int numInt = 100000;
Example:
short numShort = 1000;
Example:
long numLong = 10000000000L;
Example:
long long bigNumber = 123456789012345LL;
Example:
float numFloat = 3.14f;
Example:
double numDouble = 3.14159;
Example:
long double extendedPi = 3.14159265358979323846L;
Example:
char letter = 'A';
Example:
#include <stdbool.h> bool isValid = true;
Example:
int numbers[5] = {1, 2, 3, 4, 5};
Example:
int *ptr;
struct structure_name { type member1; type member2; // ... };
Example:
struct Person { char name[50]; int age; float salary; };
In C, booleans are typically represented using integer types, where 0 represents false and any non-zero value represents true. Let's explore how booleans are handled in C programming:
In C, there is no dedicated boolean type like in some other languages. Instead, integers (int) are commonly used to represent boolean values.
Example:
#include <stdio.h> int main() { _Bool b1 = 1; // true _Bool b2 = 0; // false printf("b1: %d\n", b1); // Output: 1 (true) printf("b2: %d\n", b2); // Output: 0 (false) return 0; }
Example:
#include <stdio.h> #include <stdbool.h> int main() { bool isValid = true; bool isReady = false; printf("isValid: %d\n", isValid); // Output: 1 (true) printf("isReady: %d\n", isReady); // Output: 0 (false) return 0; }
In C, expressions are evaluated to true (1) or false (0). Here are some examples of expressions and their boolean evaluations:
Example:
#include <stdio.h> int main() { int num = 10; float salary = 0.0; if (num) { printf("num is true\n"); } else { printf("num is false\n"); } if (salary) { printf("salary is true\n"); } else { printf("salary is false\n"); } return 0; }
Output:
num is true salary is false
In C, a null pointer is evaluated as false in boolean context. A null pointer is typically represented as (type *)0.
Example:
#include <stdio.h> int main() { int *ptr = NULL; if (ptr) { printf("ptr is not NULL\n"); } else { printf("ptr is NULL\n"); } return 0; }
Output:
ptr is NULL
In C programming, type casting refers to converting a value from one data type to another. There are two types of type casting: implicit and explicit. Let's explore each in detail:
Implicit type casting occurs automatically by the compiler when compatible types are mixed in expressions. It promotes smaller data types to larger data types to avoid loss of data. It's also known as automatic type conversion.
Example:
#include <stdio.h> int main() { int numInt = 10; double numDouble = 3.5; double result = numInt + numDouble; // Implicitly converts numInt to double printf("Result: %.2lf\n", result); // Output: 13.50 return 0; }
In this example, numInt (an integer) is implicitly converted to a double before performing the addition with numDouble.
Explicit type casting is performed by the programmer using casting operators to convert a value from one data type to another. It allows for precise control over the type conversion process but can lead to data loss if not used carefully.
Syntax:
(type) expression
Example:
#include <stdio.h> int main() { double numDouble = 3.5; int numInt; numInt = (int)numDouble; // Explicitly casts numDouble to int printf("numInt: %d\n", numInt); // Output: 3 return 0; }
In this example, numDouble (a double) is explicitly cast to an int. The decimal part is truncated, resulting in numInt being 3.
Arrays in C are collections of variables of the same type that are accessed by indexing. They provide a way to store multiple elements under a single name.
To declare an array in C, specify the type of elements it will hold and the number of elements enclosed in square brackets [].
type arrayName[arraySize];
int numbers[5]; // Array of 5 integers
Arrays can be initialized either during declaration or after declaration using assignment statements.
int numbers[5] = {1, 2, 3, 4, 5}; // Initializing during declaration // Initializing after declaration int moreNumbers[3]; moreNumbers[0] = 10; moreNumbers[1] = 20; moreNumbers[2] = 30;
Array elements are accessed using zero-based indexing, where the first element is at index 0.
int numbers[5] = {1, 2, 3, 4, 5}; printf("First element: %d\n", numbers[0]); // Output: 1 printf("Second element: %d\n", numbers[1]); // Output: 2
Array elements can be modified by assigning new values to specific indices.
int numbers[5] = {1, 2, 3, 4, 5}; numbers[2] = 10; // Modify the third element printf("Modified third element: %d\n", numbers[2]); // Output: 10
C supports multidimensional arrays, which are arrays of arrays. They are useful for storing tabular data or matrices.
int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; printf("Element at row 2, column 3: %d\n", matrix[1][2]); // Output: 6
When passing arrays to functions, C passes them by reference. This means any modifications made to the array within the function affect the original array.
#include <stdio.h> void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { int numbers[5] = {1, 2, 3, 4, 5}; printArray(numbers, 5); // Pass array and its size to function return 0; }
In C programming, strings are arrays of characters terminated by a null ('\0') character. Let's explore how to work with strings, including input, output, and manipulation:
Strings in C are arrays of characters. They can be declared and initialized in several ways:
Syntax:
char strName[size];
Example:
#include <stdio.h> int main() { // Declaring and initializing a string char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'}; // Alternatively, using string literal (implicitly adds '\0') char message[] = "Welcome"; printf("Greeting: %s\n", greeting); // Output: Hello printf("Message: %s\n", message); // Output: Welcome return 0; }
To input a string with spaces in C, fgets() from
Example:
#include <stdio.h> int main() { char name[50]; printf("Enter your name: "); fgets(name, sizeof(name), stdin); // Read input including spaces printf("Hello, %s!\n", name); return 0; }
C provides several library functions for manipulating strings, declared in
Example:
#include <stdio.h> #include <string.h> int main() { char str[] = "Hello"; int len = strlen(str); printf("Length of '%s' is %d\n", str, len); // Output: Length of 'Hello' is 5 return 0; }
Example:
#include <stdio.h> #include <string.h> int main() { char src[] = "Hello"; char dest[20]; strcpy(dest, src); printf("Copied string: %s\n", dest); // Output: Copied string: Hello return 0; }
Example:
#include <stdio.h> #include <string.h> int main() { char str1[20] = "Hello"; char str2[] = " World"; strcat(str1, str2); printf("Concatenated string: %s\n", str1); // Output: Concatenated string: Hello World return 0; }
Example:
#include <stdio.h> #include <string.h> int main() { char str1[] = "Hello"; char str2[] = "Hello"; if (strcmp(str1, str2) == 0) { printf("Strings are equal\n"); } else { printf("Strings are not equal\n"); } return 0; }
When using fgets() for string input, ensure buffer overflow doesn't occur by specifying the maximum length of input to read.
Example:
#include <stdio.h> int main() { char sentence[100]; printf("Enter a sentence: "); fgets(sentence, sizeof(sentence), stdin); // Read up to 99 characters plus '\0' printf("You entered: %s\n", sentence); return 0; }
C strings are null-terminated, meaning they end with a null character '\0'. This character indicates the end of the string and is automatically added when using string literals.
Example:
#include <stdio.h> int main() { char message[] = "Hello"; // Automatically includes '\0' // Printing characters until '\0' is encountered for (int i = 0; message[i] != '\0'; ++i) { printf("%c ", message[i]); } printf("\n"); return 0; }
Operators in C are symbols used to perform operations on variables and values. They are categorized into several types based on their functionality.
Arithmetic operators are used for basic mathematical operations.
Operator | Name | Description | Example |
---|---|---|---|
+ | Addition | Adds two operands | x + y |
- | Subtraction | Subtracts the right operand from the left | x - y |
* | Multiplication | Multiplies two operands | x * y |
/ | Division | Divides the left operand by the right operand | x / y |
% | Modulus | Returns the remainder of the division | x % y |
++ | Increment | Increases the value of operand by 1 | x++ or ++x |
-- | Decrement | Decreases the value of operand by 1 | x-- or --x |
#include <stdio.h> int main() { int a = 10, b = 3; printf("a + b = %d\n", a + b); // Output: 13 printf("a / b = %d\n", a / b); // Output: 3 printf("a %% b = %d\n", a % b); // Output: 1 (Modulus operation) int x = 5; x++; printf("x++ = %d\n", x); // Output: 6 int y = 8; y--; printf("y-- = %d\n", y); // Output: 7 return 0; }
Assignment operators are used to assign values to variables and perform operations.
Operator | Name | Description | Example |
---|---|---|---|
= | Assignment | Assigns the value on the right to the variable on the left | x = 5 |
+= | Addition | Adds right operand to the left operand and assigns the result to the left | x += 3 |
-= | Subtraction | Subtracts right operand from the left operand and assigns the result to the left | x -= 3 |
*= | Multiplication | Multiplies right operand with the left operand and assigns the result to the left | x *= 3 |
/= | Division | Divides left operand by right operand and assigns the result to the left | x /= 3 |
%= | Modulus | Computes modulus of left operand with right operand and assigns the result to the left | x %= 3 |
#include <stdio.h> int main() { int x = 10; x += 5; printf("x += 5: %d\n", x); // Output: 15 return 0; }
Comparison operators are used to compare values.
Operator | Name | Description | Example |
---|---|---|---|
== | Equal | Checks if two operands are equal | x == y |
!= | Not Equal | Checks if two operands are not equal | x != y |
> | Greater Than | Checks if left operand is greater than right | x > y |
< | Less Than | Checks if left operand is less than right | x < y |
>= | Greater Than or Equal | Checks if left operand is greater than or equal to right | x >= y |
<= | Less Than or Equal | Checks if left operand is less than or equal to right | x <= y |
#include <stdio.h> int main() { int a = 5, b = 10; printf("a == b: %d\n", a == b); // Output: 0 (false) printf("a < b: %d\n", a < b); // Output: 1 (true) return 0; }
Logical operators combine Boolean expressions.
Operator | Description | Example |
---|---|---|
&& | Logical AND | x < 5 && x < 10 |
|| | Logical OR | x < 5 || x < 4 |
! | Logical NOT | !(x < 5 && x < 10) |
#include <stdio.h> int main() { int x = 3; printf("x < 5 && x < 10: %d\n", x < 5 && x < 10); // Output: 1 (true) printf("x < 5 || x < 2: %d\n", x < 5 || x < 2); // Output: 1 (true) return 0; }
Bitwise operators perform operations on bits of integers.
Operator | Name | Description | Example |
---|---|---|---|
& | AND | Sets each bit to 1 if both bits are 1 | x & y |
| | OR | Sets each bit to 1 if one of two bits is 1 | x | y |
^ | XOR | Sets each bit to 1 if only one of two bits is 1 | x ^ y |
~ | NOT | Inverts all the bits | ~x |
<< | Left Shift | Shifts bits to the left | x << 2 |
>> | Right Shift | Shifts bits to the right | x >> 2 |