DEV Community

Cover image for C Code Snippets:)
Madhav Ganesan
Madhav Ganesan

Posted on • Originally published at madhavganesan.hashnode.dev

C Code Snippets:)

Datatypes

#include <stdio.h>

// struct datatype
struct Person {
    char name[50];
    int age;
    float salary;
};

// enum datatype
enum color {RED, GREEN, BLUE};

int main() {

    // Basic data types
    int a = 10; // 4 bytes
    float b = 5.5; //4 bytes
    char c = 'A'; //1 byte
    double d = 2.3; //8 bytes
    long double e; // 16 bytes (64-bit), 12 bytes (32-bit)
    short integer f; // 2 bytes
    long int g; //8 bytes (64-bit), 4 bytes (32-bit)


    // Array
    int arr[5] = {1, 2, 3, 4, 5};

    // Pointer
    int *ptr = &a;

    // Structure
    struct Person person1;
    person1.age = 30;
    person1.salary = 55000.50;

    // Enumeration
    enum color myColor = RED;

    // Print values
    printf("Integer: %d\n", a);
    printf("Float: %.2f\n", b);
    printf("Character: %c\n", c);
    printf("Array: %d\n", arr[0]);
    printf("Pointer: %d\n", *ptr);
    printf("Structure: Name = %s", person1.name);
    printf("Enumeration: %d\n", myColor);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Real data type:
float,double and long double

Segments of memory

  1. Text Segment (Code Segment)
    It contains the compiled machine code

  2. Data Segment
    Stores global and static variables that are initialized by the programmer.
    Two types:

Initialized Data Segment: Contains global and static variables that are explicitly initialized in the program.
Ex. int x=2;

Uninitialized Data Segment (BSS): Contains global and static variables that are not explicitly initialized.
Ex. int x;

  1. Heap
    It is used for dynamic memory allocation during runtime.

  2. Stack
    It stores local variables, function parameters, and return addresses.

Image description

Function Prototype

It is a declaration of a function that specifies the function's name, return type, and parameters, but does not provide the function body.

(Note: It is placed at the beginning of the source file and this can be many but only one definition)

#include <stdio.h>

// Function prototype with formal parameters
void func(char name[]);

int main() {
    char name[] = "Alice";
    //actual parameters
    greet(name);
    return 0;
}

// Function definition
void func(char name[]) {
    printf("Hello, %s!\n", name);
}
Enter fullscreen mode Exit fullscreen mode

MOD/modulus

This operator is used on only integer datatype. It is illegal to use modulus on float datatype

#include <stdio.h>
#include <math.h>

int main() {
    double dividend = 7.5;
    double divisor = 2.0;
    double result;
    int i=2;
    i=i%10;//works on integer types

    result = fmod(dividend, divisor);
    printf("%.1f",result); //for float types

    return 0;
}

Enter fullscreen mode Exit fullscreen mode

For loop

#include<stdio.h>
int main()
{
    int x;
    for(x=1; x<=10; x++)
    {
       // Ternary conditional operator
       a <= 20 ? (b = 30) : (c = 30);
    }
    return 0;
}

Enter fullscreen mode Exit fullscreen mode

While Loop

#include<stdio.h>
int main()
{
    int j=1;
    while(j <= 255)
    {
      j++;
    }
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

MACRO

It is a fragment of code that is given a name and can be used to perform text substitution in the code during the preprocessing phase before actual compilation.

#define PI 3.14159
#define SQUARE(x) ((x) * (x))
Enter fullscreen mode Exit fullscreen mode

Switch case

#include <stdio.h>
int main() {
    int day = 3;

    switch (day) {
        case 1:
            printf("Monday\n");
            break;
        case 2:
            printf("Tuesday\n");
            break;
        default:
            printf("Invalid day\n");
            break;
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Memory Management

Malloc: Allocates memory but does not initialize it. The memory contains garbage values.

Calloc: Allocates memory and initializes all bits to zero.

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *array;
    int size = 5;

    // Allocate memory for an array of integers
    array = (int *)malloc(size * sizeof(int));

    // Deallocate the memory
    free(array);

    int *a[3];
    a = (int*) malloc(sizeof(int)*3);
    free(a);

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Pointers

It provides a way to directly access and manipulate memory.
A pointer is a variable that stores the memory address of another variable. Instead of holding a data value directly, a pointer holds the location of the data in memory.

Basic Pointer Operations

Declaration:

int *ptr; // Declares a pointer to an integer
Enter fullscreen mode Exit fullscreen mode

Initialization:

int x = 10;
int *ptr = &x; // `ptr` now holds the address of `x`
Enter fullscreen mode Exit fullscreen mode

Dereferencing:
Access the value stored at the address pointed

int value = *ptr; // Retrieves the value of `x` via `ptr`
Enter fullscreen mode Exit fullscreen mode

Sample

#include <stdio.h>

int main() {
    int a = 5;         // Normal integer variable
    int *p = &a;       // Pointer `p` points to `a`

    printf("Value of a: %d\n", a);          // Output: 5
    printf("Address of a: %p\n", (void*)&a); // Output: address of `a`
    printf("Value of p: %p\n", (void*)p);   // Output: address of `a`
    printf("Value pointed to by p: %d\n", *p); // Output: 5

    *p = 10; // Modifies `a` through the pointer

    printf("New value of a: %d\n", a);      // Output: 10

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Pointer to a pointer

int x = 10;
int *ptr = &x;
int **pptr = &ptr; // Pointer to pointer
Enter fullscreen mode Exit fullscreen mode

Pointer to a struct

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Define a structure
struct Person {
    char name[50];
    int age;
};

int main() {
    // Declare a pointer to a structure
    struct Person *ptr;

    // Allocate memory for the structure
    ptr = (struct Person *)malloc(sizeof(struct Person));
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }

    // Use the arrow operator to access and set structure members
    strcpy(ptr->name, "Alice");
    ptr->age = 30;

    // Print structure members
    printf("Name: %s\n", ptr->name);
    printf("Age: %d\n", ptr->age);

    // Free allocated memory
    free(ptr);

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Keywords

extern

It is used to declare a global variable or function that is defined in another file or later in the same file.

#include <stdio.h>

int main() {
    extern int a;  // Accesses a variable from outside
    printf("%d\n", a);
    return 0;
}
int a = 20;
Enter fullscreen mode Exit fullscreen mode

static

Global Static Variables:
A global static variable is declared outside of any function with the static keyword.
The scope is limited to the file in which it is declared. This means it is not accessible from other files. If not explicitly initialized, a global static variable is automatically initialized to zero.

#include <stdio.h>

static int global_var = 10; // Global static variable

void display(void) {
    printf("Global variable: %d\n", global_var); // Accesses global static variable
}

int main(void) {
    display(); // Prints 10
    global_var = 20;
    display(); // Prints 20
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Local Static Variables
A local static variable is declared inside a function with the static keyword.
The scope is limited to the function in which it is declared. It cannot be accessed from outside the function.If not explicitly initialized, a local static variable is automatically initialized to zero.

#include <stdio.h>

void counter(void) {
    static int count = 0; // Local static variable
    count++;
    printf("Count: %d\n", count); // Prints the current value of count
}

int main(void) {
    counter(); // Prints 1
    counter(); // Prints 2
    counter(); // Prints 3
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Note: In C, when you have a global and a local variable with the same name, the local variable shadows (or hides) the global variable within its scope.

struct

struct book
{
    char name[10];
    float price;
    int pages;
};
Enter fullscreen mode Exit fullscreen mode

typedef

It is used to create alias name for an existing type

typedef unsigned int uint;

int main() {
    uint x = 10;  // Equivalent to unsigned int x = 10;
    printf("x = %u\n", x);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode
typedef struct Ntype {
    int i;
    char c;
    long x;
} NewType;
Enter fullscreen mode Exit fullscreen mode

Linkage

It refers to the visibility of symbols (variables and functions) across source files

External Linkage: The symbol is visible across multiple translation units (global)

Internal Linkage: The symbol is visible only within the translation unit where it is defined

None (No Linkage): The symbol is not visible outside the block in which it is defined (local variables)

Top comments (0)