ABCD of C-Programming
Wednesday, 1 November 2017
Sunday, 29 October 2017
Difference between if and switch in c
The switch statement is easy to edit
because it has created the separate cases for different statements whereas, in
nested if-else statements it become difficult to identify the statements to be
edited.
- Expression inside if statement decide whether to
execute the statements inside if block or under else block. On the other
hand, expression inside switch statement decide which case to execute.
- You can have multiple if statement for multiple choice
of statements. In switch you only have one expression for the multiple
choices.
- If-esle statement checks for equality as well as for
logical expression . On the other hand, switch checks only for equality.
- The if statement evaluates integer, character, pointer
or floating-point type or boolean type. On the other hand, switch
statement evaluates only character or a integer datatype.
- Sequence of execution is like either statement under
else block will execute or statements under if block statement will
execute. On the other hand the expression in switch statement decide which
case to execute and if you do not apply a break statement after each case
it will execute till the end of switch statement.
- It is difficult to edit if else statements as it is tedious to trace where the correction is required. On the other hand, It’s easy to edit switch statements as they are easy to trace.
- If expression turn outs to be false, statement inside else block will be executed. If expression inside switch statement turn out to be false then default statements is executed.
Friday, 13 October 2017
Difference between call by value and call by reference?
Call by Value
|
Call by
Reference
|
1) In this actual copy of arguments is passed
to formal arguments.
|
1) In this location of actual arguments is
passed to formal arguments.
|
2) Any changes made are not reflected in the
actual arguments.
|
2) Any changes made are reflected in the
actual arguments.
|
3) It can only be implemented in C, as C does
not support call by reference.
|
3) It can only be implemented in C++ and
JAVA.
|
4) Actual arguments remain preserved and no
chance of modification accidentally.
|
4) Actual arguments will not be preserved.
|
5) It works locally.
|
5) It works globally
|
#include <stdio.h>
void swapByValue(int, int); /* Prototype */
int main() /* Main function */
{
int n1 = 10, n2 = 20;
/* actual arguments will be as it is */
swapByValue(n1, n2);
}
void swapByValue(int a, int b)
{
int t;
t = a; a = b; b = t;
}
OUTPUT
======
n1: 10, n2: 20
|
#include <stdio.h>
void swapByReference(int*, int*); /* Prototype */
int main() /* Main function */ { int n1 = 10, n2 = 20;
/* actual arguments will be altered */ swapByReference(&n1, &n2); printf("n1: %d, n2: %d\n", n1, n2); }
void swapByReference(int *a, int *b) { int t; t = *a; *a = *b; *b = t; }
OUTPUT
====== n1: 20, n2: 10 |
Subscribe to:
Comments (Atom)
