Some unknown features or tricks in C language

I have found a small list of features or tricks in C language which I assume only few people would know.

1. Add any numbers without using the addition operator

Since the printf() function returns the number of characters that it prints, we could use this to add numbers as shown below:

#include <stdio.h>

int add(int a,int b){
if(a!=0&&b!=0)
return printf("%*c%*c",a,'r',b,'r');
else return a!=0?a:b;
}

int main(){
int A = 0, B = 0;
printf("Enter the two numbers to add\n");
scanf("%d %d",&A,&B);
printf("Required sum is %d",add(A,B));

return 0;
}

 

Bitwise operators could also be used to achieve the same thing as below:

int Add(int x, int y)
{
if (y == 0)
return x;
else
return Add( x ^ y, (x & y) << 1);
}

 

2. Use of Conditional Operator

We mostly use it in the following form:

x = (y < 0) ? 10 : 20;

But it could also be used as:

(y < 0 ? x : y) = 20;

3. Write a return statement in a function that returns void

static void foo (void) { }
static void bar (void) {
return foo(); // Note this return statement.
}

int main (void) {
bar();
return 0;
}

 

4. The use of comma operator:

It is used mostly in statements like:

for (int i=0; i<10; i++, doSomethingElse())
{
/* whatever */
}

 

But you can use this operator anywhere. Observe:

int j = (printf("Assigning variable j\n"), getValueFromSomewhere());

 

Each statement is evaluated, but the value of the expression will be that of the last statement evaluated.

 

5. Initializing structure to zero:

struct mystruct a = {0};

this will zero all stucture elements.

6. Multi-character constants

int x = 'ABCD';

This sets x to 0x41424344 (or 0x44434241, depending on architecture).

7. Printf in C allows you to use variables for formatting format specifiers themselves

#include <stdio.h>
int main() {
int a = 3;
float b = 6.412355;
printf("%.*fn",a,b);
return 0;
}

the * character achieves this effect.

6 thoughts on “Some unknown features or tricks in C language”

    • The first program: look at the format string in printf(), there is “%*c”.
      The “%*c” will take two parameters. the first must be an integer and the second must be a char. For an example:
      printf(“%*c”, 2, ‘a’); // equals to printf(“%2c”,’a’);
      And the printf() will return an integer indicates how many characters have been printed.

      Reply
  1. Just wanted to mention a lot of the ‘n’ characters should be ‘\n’. Not sure how the slashes would have gone missing. Delightful post either way.

    Reply

Leave a Comment