Five C Programming Hacks You Need to Know

Coding Cube
5 min readApr 17, 2021

1. Return multiple values from a function

Often we wish to get multiple return values from a function, but unlike Python, in C, Functions cannot return more than one variables. But in C, we have pointers to point out the memory locations of variables. The Pointers hold the address of variables and do some operations on it. Let’s see:

#include<stdio.h>void jargon(int *foo, int *bar){
*foo = *foo + *foo;
*bar = *bar + *bar;
}
int main()
{
int foo = 10;
int bar 20;
jargon(&foo, &bar);
//referencing address of foo and bar
printf("now foo is %d and bar is %d", foo, bar);
return 0;
}

2. Variable Number of Arguments in C function

Sometimes it comes handy to have variability in function parameters. One way you could make the function using pointer to an array. Otherwise, the C library stdarg.h provides functionalities that allows to take variable number of parameters in a function. Let’s See:

#include <stdio.h>
#include <stdarg.h>
double average(int arg_count,...){ va_list arg_list;
int sum = 0, arg_i;
double avg;
//initialization
va_start(arg_list, arg_count);
//access argument list
for(int i = 0; i < arg_count; i++){
arg_i= va_arg(arg_list, int);
sum = sum + arg_i;
}
//clear up memory assigned
va_end(arg_list);
avg = sum / arg_count; return avg;
}
int main(){
double avg;
avg = average(3, 7, 9, 1);
printf("%f", avg);
return 0;
}
Output:-5.000000

When a function have variable number of arguments, you need to place a ellipses symbol ( … ) in the last parameter of the function which tell the compiler that the function would take variable number of parameters.

These arguments will be stored in a list which type is ‘va_list’. ‘va_list’ is a datatype defined in stdarg.h header file.

va_start() is macro defined in stdarg.h header file that initialize the arg_list with the function arguments. It takes va_list variable (arg_list ) and argument counter (arg_count) as first and second parameter respectively.

va_arg() takes the va_list and a built-in variable type, and returns the next argument in the argument list in the form of that built-in variable type.

va_end() clean up the list variable and free the assigned memory.

3. Because I don’t like underscores between my name !!

In C, the concept of string is very naive. String is considered as character streams. The scanf() function could take a input string but, it accepts string only without space. After first space everything you write get discarded.

#include<stdio.h>int main()
{
char name[30];
printf("Enter your name: ");
scanf("%s", name);
printf("%s", name);

return 0;
}
Input:-Prasanta Roy ChoudhuryOutput:- Prasanta

So, with this program, when you literally want to give space between two words you have no options but underscores or other separators. your name may be look like Prasanta_Roy_Choudhury.

A messy programmer [By a naive illustrator]
#include<stdio.h>int main()
{
int len = 30;
char name[len];
printf("Enter your name: ");
fgets(name, len, stdin);
printf("%s", name);

return 0;
}
Input:- Prasanta Roy ChoudhuryOutput:- Prasanta Roy Choudhury

4. Learn a new way of writing while loop

The trivial way of writing while loop is incrementing or decrementing the value of iterator with unary operators. which is look like this:

#include<stdio.h>int main()
{
int a = 3;
while(a > 0){
printf("a= %d\n", a);
a --;
}

return 0;
}
Output:-
a= 3
a= 2
a= 1

Fancy way of writing while loop is using “goes to” operator (- ->). Though there is no such operator exist in c, the operator is mixture of two separate operators i.e , “- - ”and “>”. There is also “++” and “ < ” operator which can be used in the following code snippet:

#include<stdio.h>int main()
{
int a = 3;
while(a --> 0){
printf("a= %d\n", a);
}

return 0;
}
Output:-
a= 2
a= 1
a= 0

Did you notice something different in the output of the both code snippets??

5. Add numbers without using plus (+) operator !!

Before implementing this tricks we have to aware of few notion of printf() function. In C, the printf() function returns the number of characters it printed in the output device. We can actually use printf() function to get the addition.

#include<stdio.h>int main()
{
int count;
count = printf("Hello World\n");
printf("count: %d", count);
return 0;
}
Output:-
Hello World
count: 12

Let’s get deeper into the printf() function. The printf() function follows a specific format for printing the results. Generally, it prints the value of a variable using appropriate format specifier. A format specifier starts with % symbol. Like, for printing a character variable you need to specify the format specifier %c in printf() function.

char a = ‘A’;
printf(“%c”, a);

The format specifiers can also contain sub-specifiers: width, precision, flags and modifiers. You can find more information in this page. Generally, it follows this following structure:

%[flags][width][.precision][length]specifier

Here, we require the width sub-specifier. It determines the minimum number of characters to be printed. If the total length of the characters is less than the width then the result is padded with blank spaces.

int year = 2021;
int width = 8;
printf("%*d", width, year);
Output:-
2021

Here the asterisk symbol (*) determines the ‘width’ dynamically. Here, * symbol is replaced with the variable ‘width’ i.e, 8 that’s why the value of year printed after 4 spaces. Now, can you guess, what would be the return value for the printf() function?

Let’s create a function called add() that takes two integer parameters and return the value of printf() function.

#include<stdio.h>int add(int a, int b){
int addition;
addition = printf("%*c%*c", a, '\r', y, '\r');
return addition;
}
int main()
{
int a = 6, b = 9, sum;
sum = add(a, b);
printf("sum: %d", sum);
return 0;
}

Let’s understand it. Here in function add(), we took ‘a’ and ‘b’ as widths of the printf() function. we took ‘\r’ as a character to be printed on the output console. If the total length of the character ‘\r’ is less than the widths then the result is padded with blank spaces.

But ‘\r’ is a special escape character called Carriage Return that move the cursor to the beginning of the current line. Meaning, there will be no space in the result console but printf() function will return the value of total widths.

So the Output will be:

Output:-
sum: 15

Reference:

Thanks a lot to the authors of the following articles :)

--

--

Coding Cube

Mastering Devs. Maintained by Prasanta Roy Choudhury.