<aside>

Variable declaration & scope

int Global_variable = 10; //Global Variable(can be modified by any function)

int main(){
    //primitive datatypes are int, float, double, char, void
    //all the datatypes can also be preceded with const/volatile/static/auto/extern/register
    //int datatype can be preceded with long/short/signed/unsigned
    //char datatype can be preceded with signed/unsigned
    /*
    //extern is used in header files to make c defs compatible with cpp => 
    #ifdef __cplusplus
    extern "C" int add(int x, int y); //for cpp files
    #endif
    int add(int x, int y); // for c files
    */

    int n1; //(1) decleration
    n1 = 0; //(2) assignment
    unsigned long int n2 = 0xf1; //both (1) & (2)
    signed short int n3 = 0b1010; //binary representation
    const float n4 = 22.2;
    //const prevents changes to the value of a variable.
    volatile double n5 = 33.3;
    //volatile keyword is used to indicate that the variable's value may change unexpectedly
    //and prevents the compiler to perform any optimizations on it
    register signed char n6 = 'G';
    //register keyword is used to store the variable in CPU register

    //For storing strings just use an array of chars(there will be a null terminator char"\\0" at the end automatically)
    //C doesnt support boolean value by default(use #include <stdbool.h>)
    int x, y;
    x = y = -1; // same as python syntax
    x++, y++;

    // n[1-6], x and y are all local variables for main func

    //Creating a custom block scope
    {
        // variables of enclosing scope can be accessed & modified by enclosed scope(ie block scope)
        n5 = 99.81;
        int n1 = 88; // redeclaration of n1 is possible becasue this n1 is local to the block scope
                     // and it is shadowing the n1 present in the enclosing scope
    }
    constexpr int mello = 10 * 6 + 9;  //constant thats evaluated and available during the compilation phase
    static int jello[mello];  //if mello was just a const this wouldve resulted in compilation error
    //because constant variables are not evaluated nd present before the compilation process
    //mello will be replaced at compile time with 69 just like how a macro definition works

    return 0;
}

</aside>


<aside>

Mathematical operations & type conversion

#include <limits.h>
#include <stdbool.h>
#include <stdckdint.h>
#include <stdio.h>

int main(){
    int n1 = 10;
    int n2 = 116;
    float n3 = (float)n2 / n1;
    //dividing 2 ints will return an int thats why one of the operand needs to be typecasted
    n1++;++n1; //increments value by 1
    n1--;--n1; //decrements value by 1
    //++/-- after var means the variable will be returned then incremented/decremented & vise-versa
    n1 += 3; //n1 = n1 + 3
    n1 = 3 - n2;
    n2 %= 2; //returns the remainder of the operation n1 / 2
    n2 = n1 * n1;
    
    //C23 overflow detection feature(or you can use __builtin_add_overflow(a, b, &c) to achieve the same thing)
    int a = INT_MIN;
    int b = -10;
    int c;
    bool overflowed = ckd_add(&c, a, b);
    if(overflowed)printf("operation a + b overflowed :(\\n");
    //There are also ckd_mul, ckd_sub
    
    return 0;
}

<aside>

Standard output

#include <stdio.h>
int main(){
    long int n1 = 1;
    printf("Hello \\"World\\" %ld\\n", n1);
    printf("|%*s|\\n", -10, "Hello");
    //printf first formats the output into a string and stores it in a output buffer

    //"%" is a format specifier(think of it as a placeholder for the variable)
    //the char after "%" represents the datatype of the variable

    //d = decimal(int), ld = long decimal(long)
    //f = float(float), lf = long float(double)
    //c = character(char), s = string(char array)
    //p = used to represent the memory address stored by a pointer in hexadecimal
    //%.2f to print a float with 2 decimal points
    return 0;
}

<aside>

Standard input

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

int main(){
    int n1;char n2[20];
    scanf("%d %s", &n1, n2);  // leaves a \\n to the buffer at the end
    // reads the stdin and saves its contents to the specified variable
    // when a whitespace("\\t", "\\n", " ") is encountered
    // it moves on to saving further contents to the next specified variable and so on

    while (getchar() != '\\n'); // used to clear the input buffer

    char n3[20];
    fgets(n3, sizeof(n3), stdin); // char * fgets ( char * str, int num, FILE * stream );
    // reads chars from stream and stores them into str until num - 1 chars have been read or a newline is encountered
    // A terminating null character is automatically appended at the end
    // Note that n3 will contain the "\\n" char as well
    // On success it returns the character pointer given to it as argument
    n3[strlen(n3) - 1] = '\\0';
    printf("%d\\n%s\\n%s\\n", n1, n2, n3);
    
    char* buf = NULL;
    size_t buf_size = 0;
    getline(&buf, &buf_size, stdin);  //getline is only available on posix based OS
    //returns -1 if there's an error or EOF else returns the number of bytes read
    printf("%s\\n", buf);  //buf is null terminated nd it includes the '\\n' char
    free(buf);
            
    return 0;
}

<aside>

sizeof operator

#include <stdio.h>

int main(){
    printf("%lu\\n", sizeof(int));
    printf("%lu\\n", sizeof("Helloo"));
    return 0;
}

<aside>

Boolean expressions

#include <stdio.h>
int main(){
    int expression = (10 == 19 || 15 != 19) &&  (5 > 4 && 67 >= 9 || 9 < 3 || 5 <= 5);
    printf("%d\\n", expression);
    return 0;
}

<aside>

Conditionals

// Conditional statements are used to execute code based on the result of a boolean expression
#include <stdio.h>
#include <string.h>

int main(){
    char user_input[] = "hello";
    int is_valid = 1;
    int is_authenticated = 1;
    char user_role[] = "admin";
    int access_level = 1;
    
    if (is_valid == 1){
        if (is_authenticated == 1){
            printf("User is authenticated\\n");
        }
        else if (strcmp(user_input, "secret") == 0){
            if (strcmp(user_role, "admin") == 0) printf("Admin access granted\\n");
            else if (strcmp(user_role, "user") == 0) printf("User access granted\\n");
            else printf("Role not recognized\\n");
        }
        else if (strcmp(user_input, "exit") == 0){
            switch(access_level){
                case 1:
                case 2:
                    printf("Exiting with limited permissions\\n");  // will run if access_level is 1 or 2
                    break;
                case 3:
                    printf("Exiting with admin permissions\\n");
                    break;
                default:
                    printf("Exiting without specific permissions\\n");
            }
        }
    }
    else{
        (strcmp(user_input, "retry") == 0) ? printf("Please try again\\n"): printf("IDK\\n");
    }
    
    return 0;
}

<aside>

Loops

#include <stdio.h>

int main(){
    int i = 0, total = 0;
    do{
        total += 1;
        while (i < 70){
            i += 10;
            if (i % 3 == 0) continue;  // skips the rest of the code block and loop moves to next iteration
            total += 1;
            for(;i <= 50; i = 5*i + 2) total -= 1;
            for(int j = 0; j != 20; j += 10){
                total += 1;
                if (j == 10) break;  // stops the execution of the loop in the scope of where its called
                total += 1;
            }
        }
        i += 10;
    }while (i <= 150);

    printf("%d\\n", total);
}

<aside>

String functions

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

int main(){
    char name1[] = "1,,2,3,4,5"; //This is just a char array
    //Note the size of array should always be greater than or equal to no. of char + 1("for \\0")
    char* name2 = "abcNooOOoo\\n";
    //name2 is pointing to constant string literal saved in the BSS section of memory, name2 is not mutable
    char name3[][10] = {"ABC", "DEF", "GEH"};

    printf("%s", name1 + 1);
    printf("%lu\\n", strlen(name3[0]));
    //sep func(use strsep if you can, but its avialable on posix systems only)
    char* token = strtok(name1, ","); //replaces the first ',' it encounters with '\\0';it is modifying name1
    while (token != NULL) {
        printf("%s\\n", token);
        token = strtok(NULL, ",");
    }//Take a look at the output its important!
    
    // strncat(str1, str2, n) appends n character from str2 to str1
    // strncpy(str1, str2, n) copy n character from str2 to str1
    // strcmp(str1, str2) compares 2 strings and if they are equal return 0
    // strncmp(str1, str2, n) compares first n chars of str1 & str2 & if they are equal return 0
    // snprintf(buffer, buffer_len, "%s\\n%d\\n", "Hello", 10); => buffer = "Hello\\n10\\n"
	  //          => it also ensures that the buffer is null terminated

    return 0;
}

<aside>

Math functions