Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Wednesday, 17 July 2013

The C Language Basics Questions


1. What is a local block?
A local block is any portion of a C program that is enclosed by the left brace ({) and the right brace (}). A C function contains left and right braces, and therefore anything between the two braces is contained in a local block. An ifstatement or a switch statement can also contain braces, so the portion of code between these two braces would be considered a local block.
Additionally, you might want to create your own local block without the aid of a C function or keyword construct. This is perfectly legal. Variables can be declared within local blocks, but they must be declared only at the beginning of a local block. Variables declared in this manner are visible only within the local block. Duplicate variable names declared within a local block take precedence over variables with the same name declared outside the local block. Here is an example of a program that uses local blocks:

#include <stdio.h>
void main(void);
void main()
{
     /* Begin local block for function main() */
     int test_var = 10;
     printf("Test variable before the if statement: %d\n", test_var);
     if (test_var > 5)
     {
          /* Begin local block for "if" statement */
          int test_var = 5;
          printf("Test variable within the if statement: %d\n",
                 test_var);
          {
               /* Begin independent local block (not tied to
                  any function or keyword) */
               int test_var = 0;
               printf(
               "Test variable within the independent local block:%d\n",
               test_var);
          }
          /* End independent local block */
     }
     /* End local block for "if" statement */
     printf("Test variable after the if statement: %d\n", test_var);
}
/* End local block for function main() */
This example program produces the following output:
Test variable before the if statement: 10
Test variable within the if statement: 5
Test variable within the independent local block: 0
Test variable after the if statement: 10
Notice that as each test_var was defined, it took precedence over the previously defined test_var. Also notice that when the if statement local block had ended, the program had reentered the scope of the original test_var, and its value was 10.
2. Should variables be stored in local blocks?
The use of local blocks for storing variables is unusual and therefore should be avoided, with only rare exceptions. One of these exceptions would be for debugging purposes, when you might want to declare a local instance of a global variable to test within your function. You also might want to use a local block when you want to make your program more readable in the current context.
Sometimes having the variable declared closer to where it is used makes your program more readable. However, well-written programs usually do not have to resort to declaring variables in this manner, and you should avoid using local blocks.
3. When is a switch statement better than multiple if statements?
A switch statement is generally best to use when you have more than two conditional expressions based on a single variable of numeric type. For instance, rather than the code
if (x == 1)
     printf("x is equal to one.\n");
else if (x == 2)
     printf("x is equal to two.\n");
else if (x == 3)
     printf("x is equal to three.\n");
else
     printf("x is not equal to one, two, or three.\n");
the following code is easier to read and maintain:
switch (x)
{
     case 1:   printf("x is equal to one.\n");
                    break;
     case 2:   printf("x is equal to two.\n");
                    break;
     case 3:   printf("x is equal to three.\n");
                    break;
     default:  printf("x is not equal to one, two, or three.\n");
                    break;
}
Notice that for this method to work, the conditional expression must be based on a variable of numeric type in order to use the switch statement. Also, the conditional expression must be based on a single variable. For instance, even though the following if statement contains more than two conditions, it is not a candidate for using a switchstatement because it is based on string comparisons and not numeric comparisons:
char* name = "Lupto";
if (!stricmp(name, "Isaac"))
     printf("Your name means 'Laughter'.\n");
else if (!stricmp(name, "Amy"))
     printf("Your name means 'Beloved'.\n ");
else if (!stricmp(name, "Lloyd"))
     printf("Your name means 'Mysterious'.\n ");
else
     printf("I haven't a clue as to what your name means.\n");
4. Is a default case necessary in a switch statement?
No, but it is not a bad idea to put default statements in switch statements for error- or logic-checking purposes. For instance, the following switch statement is perfectly normal:
switch (char_code)
{
     case 'Y':
     case 'y': printf("You answered YES!\n");
               break;
     case 'N':
     case 'n': printf("You answered NO!\n");
               break;
}
Consider, however, what would happen if an unknown character code were passed to this switch statement. The program would not print anything. It would be a good idea, therefore, to insert a default case where this condition would be taken care of:
...
     default:  printf("Unknown response: %d\n", char_code);
               break;
...
Additionally, default cases come in handy for logic checking. For instance, if your switch statement handled a fixed number of conditions and you considered any value outside those conditions to be a logic error, you could insert adefault case which would flag that condition. Consider the following example:
void move_cursor(int direction)
{
     switch (direction)
     {
          case UP:     cursor_up();
                       break;
          case DOWN:   cursor_down();
                       break;
          case LEFT:   cursor_left();
                       break;
          case RIGHT:  cursor_right();
                       break;
          default:     printf("Logic error on line number %ld!!!\n",
                               __LINE__);
                       break;
     }
}

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...