Heim > Artikel > Backend-Entwicklung > C-Grundlagen
#include <stdio.h> int main() { printf("Hello, World!\n"); return 0; }
In C werden Variablen zum Speichern von Daten verwendet, die innerhalb eines Programms manipuliert werden können. Hier ist eine umfassende Anleitung zum Erstellen und Arbeiten mit Variablen in C:
Erklärung:
type variable_name;
Beispiel:
int number; char letter; float salary;
Initialisierung:
variable_name = value;
Beispiel:
number = 10; letter = 'A'; salary = 50000.0;
Deklaration und Initialisierung kombiniert:
type variable_name = value;
Beispiel:
int age = 25; double pi = 3.14159; char grade = 'A';
Beispiele:
int age; char _grade; float salary_2024;
Der Gültigkeitsbereich einer Variablen ist der Teil des Programms, in dem auf die Variable zugegriffen werden kann. Variablen in C können sein:
Lokale Variablen:Innerhalb einer Funktion oder eines Blocks deklariert und nur innerhalb dieser Funktion oder dieses Blocks zugänglich.
void myFunction() { int localVar = 5; printf("%d", localVar); }
Globale Variablen: Außerhalb aller Funktionen deklariert und von jeder Funktion innerhalb des Programms aus zugänglich.
int globalVar = 10; void myFunction() { printf("%d", globalVar); } int main() { myFunction(); // Outputs: 10 return 0; }
Konstanten sind Variablen, deren Werte nach der Zuweisung nicht mehr geändert werden können. Sie werden mit dem Schlüsselwort const deklariert.
Beispiel:
const int DAYS_IN_WEEK = 7; const float PI = 3.14159;
In C enthalten nicht initialisierte lokale Variablen Müllwerte, während globale und statische Variablen standardmäßig auf Null initialisiert werden.
Beispiel:
#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; }
Sie können mehrere Variablen desselben Typs in einer einzigen Zeile deklarieren und sie durch Kommas trennen. Sie können sie auch entweder zum Zeitpunkt der Deklaration oder später initialisieren.
Beispiele:
// Declaring multiple variables without values int a, b, c; // Declaring and initializing some variables int x = 10, y, z = 30;
Sie können mehreren Variablen denselben Wert zuweisen, indem Sie den Zuweisungsoperator verketten.
Beispiel:
int m, n, o; m = n = o = 50;
Kommentare in C sind nicht ausführbare Anweisungen, die zur Beschreibung und Erläuterung des Codes verwendet werden. Sie sind wichtig, um den Code lesbarer und wartbarer zu machen. C unterstützt zwei Arten von Kommentaren:
Einzeilige Kommentare beginnen mit zwei Schrägstrichen (//). Alles, was in dieser Zeile auf // folgt, gilt als Kommentar.
Syntax:
// This is a single-line comment int x = 10; // x is initialized to 10
Mehrzeilige Kommentare beginnen mit /* und enden mit */. Alles zwischen /* und */ gilt als Kommentar, unabhängig davon, wie viele Zeilen er umfasst.
Syntax:
/* This is a multi-line comment. It can span multiple lines. */ int y = 20; /* y is initialized to 20 */
Beispiel für einen einzeiligen Kommentar:
#include <stdio.h> int main() { // Print Hello, World! printf("Hello, World!\n"); // This prints the string to the console return 0; }
Beispiel für einen mehrzeiligen Kommentar:
#include <stdio.h> int main() { /* This is a simple C program that prints Hello, World! to the console. */ printf("Hello, World!\n"); return 0; }
Diese Beispiele veranschaulichen, wie einzeilige und mehrzeilige Kommentare in C verwendet werden, um den Code lesbarer und wartbarer zu machen.
In C werden Eingabe- und Ausgabeoperationen mithilfe von Standardbibliotheksfunktionen ausgeführt. Die am häufigsten verwendeten Funktionen für die grundlegende Ein- und Ausgabe sind printf und scanf.
Die printf-Funktion wird verwendet, um Text und Variablen auf der Konsole zu drucken.
Syntax:
printf("format string", variable1, variable2, ...);
Formatbezeichner:
Beispiel:
#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; }
Die Scanf-Funktion wird verwendet, um formatierte Eingaben von der Konsole zu lesen.
Syntax:
scanf("format string", &variable1, &variable2, ...);
Beispiel:
#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; }
Eine Textzeile mit fgets lesen:
Syntax:
fgets(buffer, size, stdin);
Beispiel:
#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 Beispiel:
#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 |