Here is a listing of C Objective Questions on “Declarations” along with answers, explanations and/or solutions:
1. What will be the output of the following C code?
-
#include
-
void foo(const int *);
-
int main()
-
{
-
const int i = 10;
-
printf("%d ", i);
-
foo(&i);
-
printf("%d", i);
-
-
}
-
void foo(const int *i)
-
{
-
*i = 20;
-
}
a) Compile time error
b) 10 20
c) Undefined value
d) 10
Answer: a
Clarification: Cannot change a const type value.
Output:
$ cc pgm1.c
pgm1.c: In function ‘foo’:
pgm1.c:13: error: assignment of read-only location ‘*i’
2. What will be the output of the following C code?
-
#include
-
int main()
-
{
-
const int i = 10;
-
int *ptr = &i;
-
*ptr = 20;
-
printf("%dn", i);
-
return 0;
-
}
a) Compile time error
b) Compile time warning and printf displays 20
c) Undefined behaviour
d) 10
Answer: b
Clarification: Changing const variable through non-constant pointers invokes compiler warning.
Output:
$ cc pgm2.c
pgm2.c: In function ‘main’:
pgm2.c:5: warning: initialization discards qualifiers from pointer target type
$ a.out
20
3. What will be the output of the following C code?
-
#include
-
int main()
-
{
-
j = 10;
-
printf("%dn", j++);
-
return 0;
-
}
a) 10
b) 11
c) Compile time error
d) 0
Answer: c
Clarification: Variable j is not defined.
Output:
$ cc pgm3.c
pgm3.c: In function ‘main’:
pgm3.c:4: error: ‘j’ undeclared (first use in this function)
pgm3.c:4: error: (Each undeclared identifier is reported only once
pgm3.c:4: error: for each function it appears in.)
4. Will the following C code compile without any error?
-
#include
-
int main()
-
{
-
for (int k = 0; k < 10; k++);
-
return 0;
-
}
a) Yes
b) No
c) Depends on the C standard implemented by compilers
d) Error
Answer: c
Clarification: Compilers implementing C90 do not allow this, but compilers implementing C99 allow it.
Output:
$ cc pgm4.c
pgm4.c: In function ‘main’:
pgm4.c:4: error: ‘for’ loop initial declarations are only allowed in C99 mode
pgm4.c:4: note: use option -std=c99 or -std=gnu99 to compile your code
5. Will the following C code compile without any error?
-
#include
-
int main()
-
{
-
int k;
-
{
-
int k;
-
for (k = 0; k < 10; k++);
-
}
-
}
a) Yes
b) No
c) Depends on the compiler
d) Depends on the C standard implemented by compilers
Answer: a
Clarification: There can be blocks inside the block. But within a block, variables have only block scope.
Output:
$ cc pgm5.c
6. Which of the following declaration is not supported by C?
a) String str;
b) char *str;
c) float str = 3e2;
d) Both String str; & float str = 3e2;
Answer: a
Clarification: It is legal in Java, but not in C.
7. Which of the following format identifier can never be used for the variable var?
-
#include
-
int main()
-
{
-
char *var = "Advanced Training in C by .com";
-
}
a) %f
b) %d
c) %c
d) %s
Answer: a
Clarification: %c can be used to print the indexed position.
%d can still be used to display its ASCII value.
%s is recommended.
%f cannot be used for the variable var.