Home »
Aptitude Questions and Answers »
C Aptitude Questions and Answers
C Functions and Blocks - Aptitude Questions & Answers
C programming Functions and Blocks Aptitude Questions and Answers: In this section you will find C Aptitude Questions and Answers on Functions and Blocks – Scope of the block, function’s declarations, function’s definition, function’s calling etc.
1) What will be the output of following program ?
#include <stdio.h>
int main()
{
int var=100;
{
int var=200;
printf("%d...",var);
}
printf("%d",var);
return 0;
}
- ERROR
- 200...200
- 100...100
- 200...100
Correct Answer - 4
200...100
You can define blocks with in the funtion body by using { .. }, int var=200; is global in main function
for block defined in main() body and int var=100; is local for same block.
2) What will be the output of following program ?
#include <stdio.h>
char* fun1(void)
{
char str[]="Hello";
return str;
}
char* fun2(void)
{
char *str="Hello";
return str;
}
int main()
{
printf("%s,%s",fun1(),fun2());
return 0;
}
- ERROR
- Hello,Hello
- Hello,Garbage
- Garbage,Hello
Correct Answer - 4
Garbage,Hello
fun1() suffers from the dangling pointer, The space for "Hello" is created dynamically as the
fun1() is called, and is also deleted on the exiting of the function fun1(), so that data is not available in
calling function (main()).
3) What will be the output of following program ?
#include <stdio.h>
int fooo(void)
{
static int num=0;
num++;
return num;
}
int main()
{
int val;
val=fooo();
printf("step1: %d\n",val);
val=fooo();
printf("step2: %d\n",val);
val=fooo();
printf("step3: %d\n",val);
return 0;
}
- step1: 1
step2: 1
step3: 1
- step1: 1
step2: 2
step3: 3
- step1: 0
step2: 0
step3: 0
- ERROR
Correct Answer - 2
step1: 1
step2: 2
step3: 3
The life time of a static variable is the entire program i.e. when we call fooo() again num will not declare again.
4) What will be the output of following program ?
#include <stdio.h>
int main()
{
int anyVar=10;
printf("%d",10);
return 0;
}
extern int anyVar;
- Compile time error
- 10
- Run time error
- None of these
Correct Answer - 2
10
The extern variable cannot initialize with block scope, and you are free to declare them outside of
block scope, extern makes the variable accessible in other files.