Category Archives: C/C++ Puzzles

__attribute__((constructor)) and __attribute__((destructor)) syntaxes in C

Write two functions in C using GCC compiler, one of which executes before main function and other executes after the main function. GCC specific syntaxes : 1. __attribute__((constructor)) syntax : This particular GCC syntax, when used with a function, executes the same function at the startup of the program, i.e before main() function. 2. __attribute__((destructor))… Read More »

Nested printf (printf inside printf) in C

Predict the output of the following C program with a printf inside printf. Output : 198741 Explanation : 1. Firstly, the innermost printf is executed which results in printing 1987 2. This printf returns total number of digits in 1987 i.e 4. printf() returns number of characters successfully printed on screen. The whole statement reduces… Read More »

auto_ptr, unique_ptr, shared_ptr and weak_ptr

Prerequisite – Smart Pointers C++ libraries provide implementations of smart pointers in following types: auto_ptr unique_ptr shared_ptr weak_ptr They all are declared in memory header file. auto_ptr This class template is deprecated as of C++11. unique_ptr is a new facility with a similar functionality, but with improved security. auto_ptr is a smart pointer that manages… Read More »

Interesting Facts in C Programming

Below are some interesting facts about C programming: 1) The case labels of a switch statement can occur inside if-else statements. Output : GeeksforGeeks 2) arr[index] is same as index[arr] The reason for this to work is, array elements are accessed using pointer arithmetic. Output : 1 3) We can use ‘<:, :>’ in place… Read More »

Dangling, Void , Null and Wild Pointers

  Dangling pointer A pointer pointing to a memory location that has been deleted (or freed) is called dangling pointer. There are three different ways where Pointer acts as dangling pointer De-allocation of memory Function Call Output: A garbage Address The above problem doesn’t appear (or p doesn’t become dangling) if x is a static… Read More »

Execution of printf with ++ operators

Consider below C++ program and predict its output. The above invokes undefined behaviour by referencing both ‘i’ and ‘i++’ in the argument list. It is not defined which order the arguments are evaluated. Different compilers may choose different orders. A single compiler can also choose different orders at different times. For example below three printf… Read More »