{"id":19829613,"url":"https://github.com/debakarr/c-snippets","last_synced_at":"2025-07-25T09:03:36.741Z","repository":{"id":92256358,"uuid":"123308358","full_name":"debakarr/C-Snippets","owner":"debakarr","description":"This repository contains few code snippets for C language which I thing might worth knowing.","archived":false,"fork":false,"pushed_at":"2018-03-04T14:31:43.000Z","size":11,"stargazers_count":6,"open_issues_count":0,"forks_count":0,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-05-01T14:45:07.537Z","etag":null,"topics":["c","interview","macros","pointers","snippets"],"latest_commit_sha":null,"homepage":null,"language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/debakarr.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2018-02-28T16:03:18.000Z","updated_at":"2022-07-01T17:05:43.000Z","dependencies_parsed_at":"2023-06-08T04:15:22.570Z","dependency_job_id":null,"html_url":"https://github.com/debakarr/C-Snippets","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/debakarr/C-Snippets","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/debakarr%2FC-Snippets","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/debakarr%2FC-Snippets/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/debakarr%2FC-Snippets/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/debakarr%2FC-Snippets/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/debakarr","download_url":"https://codeload.github.com/debakarr/C-Snippets/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/debakarr%2FC-Snippets/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":266983423,"owners_count":24016553,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-07-25T02:00:09.625Z","response_time":70,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["c","interview","macros","pointers","snippets"],"created_at":"2024-11-12T11:19:21.951Z","updated_at":"2025-07-25T09:03:36.724Z","avatar_url":"https://github.com/debakarr.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"### This repository contains few code snippets for C language which I thing might worth knowing.\n\n#### If you like this please considering giving it a :star: (top right) :sweat_smile:\n\n***\n\n##### General code snippets\n\n\n* **Will this code run? If yes what is it going to return?**\n\n```C\nint main(){\n    printf(\"Hello World!\");\n}\n```\n\n**Answer:** Yes this will run in C (not C++). C compiler will create an implicit declaration for the function printf(), compile this code into an object file. This is going to return 0. You can check it using ```echo $?```.\n\n***\n\n* **Swap 2 variables without using temporary variable**\n\nUsing '+' and '-':\n\n```C\na = a + b;\nb = a - b;\na = a - b;\n```\n\nOR\n\nUsing '\\*' and '/':\n\n```C\na = a * b;\nb = a / b;\na = a / b;\n```\n\nOR\n\nUsing ^ (ex-or):\n\n```C\na = a ^ b;\nb = a ^ b;\na = a ^ b;\n```\n\n***\n\n* **Implementation of strlen**\n\n```C\nint impStrlen (char *str) {\n\n\t// pointer to the starting address of str\n\tchar *temp= str ;\n\twhile (*temp++)\n\t\t// You can print value of temp to get an idea of what is happening\n\t\t//printf(\"%d\\n\", temp);\n\t\t;\n\n\treturn (temp - str - 1 );\n}\n```\n\n***\n\n* **Check if string is palindrome or not**\n\n```C\nint palindromeCheck (char *str){\n\tchar *p1 = str; // pointer pointing to starting of the string\n\tchar *p2 = str + strlen (str) - 1; // pointer pointing to ending of the string\n\n\twhile (p1 \u003c p2){\n\t\tif (*p1++ != *p2--)\n\t\t\treturn 0;\t\t// not a palindrome\n\t}\n\n\treturn 1;\t\t\t// it is a palindrome\n}\n```\n\n***\n\n* **Set or reset a specific bit in a given variable**\n\ne.g. \n\n8 -\u003e 1000\n\nwe want to set 0th position so that it become 1001 (i.e. 9)\n\n3 -\u003e 0011\n\nwe want to reset 0th position so that it becomes 0010 (i.e. 2)\n\n```C\n#include \u003cstdio.h\u003e\n\n// We can do a bitwise AND (\u0026) or OR (|) to reset or set the bit\n#define BITWISE_OP(x) (0x1 \u003c\u003c x)\n\nint set(int val, int pos){\n    return (val |= BITWISE_OP(pos)) ;\n}\n\nint reset(int val, int pos) {\n    return (val \u0026= ~BITWISE_OP(pos)) ;\n}\n\nint main (){\n  \n    printf(\"%d\\n\", set(8,0));\n    printf(\"%d\\n\", reset(3,0));\n\n  return 0;\n}\n```\n\nOutput is:\n\n9\n\n2\n\n***\n\n* **We can use bitwise operators in many situation**\n\nRewriting **int c = a \\* 16 + b / 2;**\n\n```C\nint c = (a \u003c\u003c 4) + (b \u003e\u003e 1)\n```\n\n***\n\n* **Complement of integer without directly using** **~**\n\nrefer to this: https://stackoverflow.com/questions/791328/how-does-the-bitwise-complement-operator-work\n\n```C\n#include \u003cstdio.h\u003e\n\nvoid complement(int i) {\n    printf( \"Method 1: %d\\n\", i^(~0));\n    printf( \"Method 2: %d\\n\" , -(i+1)) ;\n}\n\nint main (){\n    complement(5);\n    return 0;\n}\n```\n\n***\n\n* **Multiline macros**\n\nIt is best practice to set a pointer to NULL after freeing it. We can use a macros for this. Below is the code for the same. \n\n```C\n#include \u003cstdio.h\u003e\n#include \u003cstdlib.h\u003e\n#define freeNULL(p) {free(p); p = NULL; printf(\"FIN\");}\n\nint main (){\n    \n    int *ptr = (int *) malloc( 1 * sizeof(int *) );\n    \n    if(1)\n        freeNULL(ptr);\n    else\n        printf(\"Nothing to do here...\");\n        \n    return(0);\n}\n```\n\nBut this code gives an error message:\n\n```\nIn function 'main':\n12:5: error: 'else' without a previous 'if'\n     else\n     ^~~~\n```\n\nwhy so?\n\nThe reson is that after puting the macros the if statement becomes something like this:\n\n```C\nif(1){\n\tfree(p); \n\tp = NULL; \n    printf(\"FIN\");\n};\n```\n\nThe semicolon at the end cause the error. The Best way to overcome this is to use a do-while(0) loop. This loop runs only once, and after using this loop the if statement becomes something like this:\n\n```C\nif(1)\ndo {\n\tfree(p); \n\tp = NULL; \n    printf(\"FIN\");\n}while(0);\n```\n\nSo our program looks like:\n\n```C\n#include \u003cstdio.h\u003e\n#include \u003cstdlib.h\u003e\n#define freeNULL(p) do{free(p); p = NULL; printf(\"FIN\");}while(0)\n\nint main (){\n    \n    int *ptr = (int *) malloc( 1 * sizeof(int *) );\n    \n    if(1)\n        freeNULL(ptr);\n    else\n        printf(\"Nothing to do here...\");\n        \n    return(0);\n}\n```\n\n***\n\n* **Find size of a variable without using** _sizeof_ **operator**\n\n\n\n```C\n#include \u003cstdio.h\u003e\n#define mySizeof(x) (((x *) 0) + 1)\n\nint main(){\n    printf(\"%zd\\n\", mySizeof(char));\n    printf(\"%zd\\n\", mySizeof(int));\n    printf(\"%zd\\n\", mySizeof(float));\n    printf(\"%zd\\n\", mySizeof(double));\n}\n```\n\n***\n\n* **Swap two nibbles in a byte**\n\nbefore swap:\n\n18 -\u003e 0001 0010\n\nafter swap:\n\n0010 0001 -\u003e 33 \n\n```C\n#include \u003cstdio.h\u003e\n#define swap(x) (((x \u0026 0xF) \u003c\u003c 4 ) | ((x\u00260xF0) \u003e\u003e 4))\n\nint main(){\n    printf(\"%d\\n\", swap(18));\n}\n```\n\n***\n\n* **Find middle node in a singly linked list**\n\nThe idea is to take two pointers pointing to head. Now increament 1st pointer by 1 and 2nd pointer by 2 in each iteration. When the 2nd pointer reach the end of the linked list then the first pointer is pointing to middle node.\n\n```C\nNode *middleNode(Node *head){\n    Node *p1 = head, *p2 = head;\n\n    while(p2 != 0){\n        p1 = p1-\u003enext;\n        p2 = (p2-\u003enext) ? p2-\u003enext-\u003enext : 0;\n    }\n\n    return p1;\n}\n```\n\n***\n\n* **Check if the number is power of 2**\n\nAny number which is power of 2  and the number 1 less returns 0 when we apply a bitwise AND (\u0026) operation.\n\ne.g. \n\n8 -\u003e 1000\n\n7 -\u003e 0111\n\nand (1000 \u0026 0111) = 0000\n\n```C\ncheckIfPowerOf2(int n){\n    return(!(n \u0026 (n-1)));\n}\n```\n\n***\n\n* **Delete a node in a linked list, pointer to which is given**\n\n```C\nvoid deleteNode(Node *node){\n\t// traverse the list till the end keep on copying the next node to the current node\n\twhile(node != NULL){\n\t\tnode.data = node-\u003enext.data;\n\t\tnode = node-\u003enext;\n\t}\n}\n```\n\nThis way the time complexity is O(n). Another way of doing this is just copy the next node detail in the current node and free the next node. But in this way you need to make sure that a next node is present in the list. This way the time complexity is O(1).\n\n```C\nvoid deleteNode(Node *node){\n\tif(node-\u003enext != NULL){\n\t\t// copy data of next node\n\t\tnode.data = node-\u003enext.data;\n\t\t// get pointer to the next node\n\t\tNode *freeNode = node-\u003enext;\n\t\t// copy pointer to the next to next node\n\t\tnode-\u003enext = node-\u003enext-\u003enext;\n\t\t// free next node\n\t\tfree(freeNode);\n\t}\n}\n```\n\n***\n\n* **How would you know whether your system is Big-endian or Little-endian**\n\nThe order in which the variable is stored in machine referred to as endian.\n\nSequence order -\u003e big endian\n\nReverse order -\u003e little endian\n\nEg. take hex number 0x0304\n\nMachine A stores 2 bytes at a time and the sequence of store is: 0x03 followed by 0x04\n\nMachine B stores 2 bytes at a time and the sequence of store is: 0x04 followed by 0x03\n\nTherefore \n\nmachine A -\u003e big endian\n\nmachine B -\u003e little endian\n\n```C\n#include \u003cstdio.h\u003e\n\nint main(){\n    \n    // This is a very nice example to demostrate the use of union\n    // In union all member shares same memory location\n    union{\n        short value;\n        char store[sizeof(short)];\n    } endianCheck;\n    \n    endianCheck.value = 0x0304;\n    \n    // Here endianCheck share same memory location as of value\n    if(endianCheck.store[0] == 0x03 \u0026\u0026 endianCheck.store[sizeof(short) - 1] == 0x04)\n        printf(\"big-endian system\");\n    else\n        printf(\"little-endian system\");\n\n    return 0;\n}\n```\n\n***\n\n* **Find if a number is power of two**\n\nThe logic is very straight forward.\n\n2 =\u003e 0010; 2-1 (i.e. 1) =\u003e 0001; 2 \u0026 1 =\u003e 0010 \u0026 0001 = 0000\n\n4 =\u003e 0100; 4-1 (i.e. 3) =\u003e 0011; 4 \u0026 3 =\u003e 0100 \u0026 0011 = 0000\n\n8 =\u003e 1000; 8-1 (i.e. 7) =\u003e 0111; 8 \u0026 7 =\u003e 1000 \u0026 0111 = 0000\n...\n\n```C\nint isPowerOf2(int num){\n\treturn(!(num \u0026 (num -1)));\n}\n```\n\n***\n\n* **Very interesting code. Print binary representation of any number. Let's do it recursively.**\n\n```C\n#include \u003cstdio.h\u003e\n\nvoid decimalToBinary(int num){\n\tif(num == 0)\n\t\treturn;\n\tdecimalToBinary(num \u003e\u003e 1);\n\t(num \u0026 01) ? printf(\"1\") : printf(\"0\");\n\n}\n\nint main(){\n    \n    decimalToBinary(965);\n\n    return 0;\n}\n```\n\nOutput: 1111000101\n\n***\n\n* **Check if implemetation of shift operator (\u003e\u003e) follows logical shift or arithematic shift.**\n\nThe results are implementation-dependent for right shifts of signed values.\n\n**Logical right shift**: 1 bit shifts all the bits to the right and fills in the leftmost bit with a '0'. \n\n**Arithmetic right shift**:  1 bit shifts all the bits to the right and fills in the leftmost bit with original value of the right mst bit shifted.\n\ne.g.\n\n1 bit Logical Right Shift \n\n```C\nunsigned char x = x \u003e\u003e 1;\n```\n\nBefore:  00010000    ( = 16 decimal )\n\nAfter:   00001000    ( = 8 decimal )\n\nBefore:  01001001\n\nAfter:   00100100    ( one bit is \"lost\". LSB of original data)\n\nBefore:  10000001    ( = 129 decimal )\n\nAfter:   01000000    ( = 64 decimal - one bit is \"lost\")\n\n1 bit Arithmetic Right Shift\n\n```C\nsigned char x = x \u003e\u003e 1;\n```\n\nBefore:  00001000    ( = 8 decimal )\n\nAfter:   00000100    ( = 4 decimal )\n\nBefore:  10000011    ( = -125 decimal in two's complement )\n\nAfter:   11000001    ( = -63 decimal )\n\nAfter:   11100000    ( = -32 decimal )\n\nAfter:   11110000    ( = -16 decimal )\n\nAfter:   11111000    ( = -8 decimal )\n\nAfter:   11111100    ( = -4 decimal )\n\nAfter:   11111110    ( = -2 decimal )\n\nAfter:   11111111    ( = -1 decimal )\n\nAfter:   11111111    ( = -1 decimal )\n\nMore info: http://teaching.idallen.com/dat2343/09f/notes/04bit_operations_shift.txt\n\nUse:\n\nLogical shift: Used in serial data communication to transfer the data bit by bit or for multiplying unsigned numbers by power of 2.\n\nArithematic shift: Used in signed arithmetic computations.\n\nSo the program?\n\n```C\nint main(){\n\t((-1 \u003e\u003e 1) \u003c 0) ? printf(\"Arithematic shift\") : printf(\"Logical shift\");\n}\n```\n\n***\n\n* **Output of the code?**\n\n```C\nint main(){\n    printf(\"%d\\n\", 1 \u003c 2 \u003c 3);\n    printf(\"%d\\n\", 3 \u003e 2 \u003e 1);\n}\n```\n\n**Output:**\n```\n1\n0\n```\n\nFor 1st printf(), ( 1 \u003c 2 ) is 1 and ( 1 \u003c 3 ) is true hence 1 is printed.\nFor 2nd printf(), ( 3 \u003e 2) is 1 and (1 \u003e 1) is false (0), and hence 0 is printed.\n\n***\n\n* **Output of the code?**\n\n```C\nint main(){\n    int i = 1;\n    \n    printf(\"%d\", ++i++);\n}\n```\n\n```diff\n- error: lvalue required as increment operand\n```\n\n(++i) is a *rvalue* expression and postfix ++ requires an *lvalue*, hence error.\n\nGenerally *lvalue* is objects that occupies some identifiable memory location.\n\neg.\n\n```C\nint a = 7;\n```\n\n**a** is a lvalue\n\n```C\n4 = b;       // error!\n(b + 1) = 4; // error!\n```\n\n**b+1 and 4 both are not lvalue which makes them rvalue.** \n\n***\n\n* **Output of the code?**\n\n```C\nint main(){\n    int i = 1;\n    int *ptr = \u0026i;\n    \n    printf(\"%d\", ++*ptr++);\n}\n```\n\n**Output:** 2\n\nWhen we combine prefix **++** with dereferencing operator **\\*** we get a result which is a *lvalue* i.e **(++\\*ptr)** and the value is now **2**. Now postfix ++ needs a *lvalue* which is available so it's fine. Though there is no immediate effect of postfix ++, hence the value printed is still **2**.\n\n***\n\n* **Output of the code?**\n\n```C\nint main(){\n    int i = 3;\n\n    printf(\"%d\", ~!-+~i);\n}\n```\n\n**Output:** -1\n\nReason:\n\n~i = -4\n\n+~i does not have any effect because **+** is **dummy operator** in C.\n\n-+~i = 4\n\n!-+~i = 0 i.e. negation of any non zero value is 0\n\n~!-+~i = -1 i.e. ~0 = -1\n\n***\n\n##### Some mistakes\n\n```C\n#include \u003cstdio.h\u003e\nint main(){\n    int * const i = 20;\n    \n    printf(\"%d\", *++i);\n\n    return 0;\n}\n```\n\n```diff\n- error: increment of read-only variable 'i'\n```\n\nReason: We are trying to change the value of constant pointer.\n\n***\n\n```C\n#include \u003cstdio.h\u003e\n\nint main(){\n    float f = 2.0 * 3.0 - 6.0 + 1.0;\n    \n    switch(f){\n        case 1.0:\n            printf(\"%f\", 1.0);\n            break;\n        case 2.0:\n            printf(\"%f\", 2.0);\n            break;\n        default:\n            printf(\"%f\", f);\n    }\n}\n```\n\n```diff\n- error: switch quantity not an integer\n- error: case label does not reduce to an integer constant\n```\n\nReason: Switch/case can only accept integers.\n\n***\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdebakarr%2Fc-snippets","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdebakarr%2Fc-snippets","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdebakarr%2Fc-snippets/lists"}