Lesser known Concepts in C

Hi Reader!

In this blog I am going to share some of the less known concepts in C language, however if we know these concepts they’ll seem obvious to us. Nevertheless for the ones who don’t know these concepts, here are some of them which I found on some blog or reading somewhere:

Note: Some of the compilers may not support the concepts shown below.

  • We can ignore input in scanf() by using an ‘*’ after ‘%’ in format specifiers
int main()
 {

int a;

// If the input is 3 4, we get output as 4
 // First one is ignored
 // If we remove * from below line, we'll get 3
 scanf("%*d%d", &a);

printf("%d ", a);

return 0;

}
  • We can use ranges in switch cases
#include<stdio.h>
 int main()
 {

int a = 2;
 switch (a)
 {

case 'A' ... 'Z': //do something

break;

case 1 ... 5:
 printf("hello");
 }
 return 0;

}

// output will be hello

  • Argument index specification in printf() format specifier
#include<stdio.h >



void main()   


{
 

  printf( "%4$d  %3$d  %2$d  %1$d ",  1,  2,  3,  4);    


}

//Output will be 4 3 2 1

  • Using #include at strange places

Let “text.txt” contains (“Hello Reader!”);

#include<stdio.h>

int main()

{

    printf#include "text.txt"

    

}

Output will be: Hello Reader!

  • The case labels of a switch statement can occur inside if-else statements
int main()

{

    int a = 20, b = 200;

    switch(a)

    {

    case 1:

        ;

 

        if (b==5)

        {

        case 2:

            printf("Hello Reader!");

        }

    else case 3:

    {

 

    }

    }

}
  • ‘<:, :>, <%, %>’ in place of ‘[, ], {, }’, Earlier, it was hard to write ‘[, ], {, }’, C actually accepted ‘<:, :>, <%, %>’ respectively
int main() <%

    int a <: 2 :>;

    a<:0:>=1;

    printf("%d",a<:0:>);

    return 0;

%>
  • The mystery of comma operator
int main(void)

{

    int a = 1, 2, 3;

    printf("%d", a);

    return 0;

}

The above program fails in compilation, but the following program compiles fine and prints 1.

intmain(void)

{

    inta;

    a = 1, 2, 3;

    printf("%d", a);

    return0;

}

And the following program prints 3, why?

intmain(void)

{

    inta;

    a = (1, 2, 3);

    printf("%d", a);

    return0;

}

In a C/C++ program, comma is used in two contexts: (1) A separator (2) An Operator.
Comma works just as a separator in PROGRAM 1 and we get compilation error in this program.
Comma works as an operator in PROGRAM 2. Precedence of comma operator is least in operator precedence table. So the assignment operator takes precedence over comma and the expression “a = 1, 2, 3″ becomes equivalent to “(a = 1), 2, 3″. That is why we get output as 1 in the second program. For the third one associativity comes into the picture.

 

Hope you enjoyed reading.

Happy Coding! 🙂

Adios!

 

 

Leave a comment

Create a free website or blog at WordPress.com.

Up ↑