Sunday, July 1, 2018

C Questions And Answers – 2018A1

 

There are many commonly asked questions regarding C programming language. Below are some collected such question-answer examples. The questions are usually related with Turbo C IDE in windows or GCC under Linux environment [not always].

For more such examples, click C_Q&A label.

 

-------------------------------------------------------------------------------------------------

 

How do I write code that executes certain function only at program termination?

 

Ans:

Use atexit( ) function as shown in following program.

 

#include <stdlib.h>

 

main( )

{

int ch ;

void fun ( void ) ;

atexit ( fun ) ;

// code

}

void fun( void )

{

printf ( "\nTerminate program......" ) ;

getch( ) ;

}

 

-------------------------------------------------------------------------------------------------

 

What will be the output of the following code?

 

void main ()

{

int i = 0 , a[3] ;

a[i] = i++;

printf (“%d",a[i]) ;

}

 

Ans:

The output for the above code would be a garbage value. In the statement a[i] = i++; the value of the variable i would get assigned first to a[i] i.e. a[0] and then the value of i would get incremented by 1. Since a[i] i.e. a[1] has not been initialized, a[i] will have a garbage value.

 

-------------------------------------------------------------------------------------------------

 

Why doesn't the following code give the desired result?

 

int x = 3000, y = 2000 ;

long int z = x * y ;

 

Ans:

Here the multiplication is carried out between two ints x and y, and the result that would overflow would be truncated before being assigned to the variable z of type long int. However, to get the correct output, we should use an explicit cast to force long arithmetic as shown below:

 

long int z = ( long int ) x * y ;

 

Note that ( long int )( x * y ) would not give the desired effect.

 

-------------------------------------------------------------------------------------------------

 

Why doesn't the following statement work?

 

char str[ ] = "Hello" ;

strcat ( str, '!' ) ;

 

Ans:

The string function strcat( ) concatenates strings and not a character. The basic difference between a string and a character is that a string is a collection of characters, represented by an array of characters whereas a character is a single character. To make the above statement work writes the statement as shown below:

 

strcat ( str, "!" ) ;

 

-------------------------------------------------------------------------------------------------

 

…till next post, bye-bye & take care.

No comments:

Post a Comment