C Questions
C Questions
C Questions
interviews
Comment on the output of following C code:
#include <stdio.h>
int main(){
const int x=10;
int *p;
p=&x;
*p=20;
printf("%d %d",*p, x);
getch();
return 0;
}
Answer: We are trying to change the value of a const variable. Such code may
lead to unknown behaviour in program depending on compiler used. In Dev C++ code compiles with
warning and produces output 20 20. Thus value of a constant is being changed through pointers. Such
error can be prevented if we make use of pointer to constant to store the address of x instead of a
simple integer pointer. If we use int const *p=&x; then *p=20 will produce a compilation error.
printf("atandon"+1);//P
printf("a%d%d%d"+2,1,2); //Q
Answer & Explanation
P : tandon
+1 removes 1 char from format specifier string.
Q: d12
+2willremove'a'andfirst%fromformatspecifiers,remaining%dwillbereplaced
bycorrespondingvalues=>d12
#if!defined(RSA)insteadof#ifndefRSA
Question: What is the use of # in macro functions?
Answer: It is used to return the string equivalent of the passed parameter. Consider the following
example:#define debug(exp) printf(#exp " =%f",exp);
Now debug(x/y); will convert to printf("x/y" " =%f",x/y);
Thiswillprint:x/y=<valueofx/yinfloat>
Question: Explain use of ## in macros.
Answer:
let's say you have
#define dumb_macro(a,b) a ## b
Now if you call the above macro as dumb_macro(hello, world)
It would result in
helloworld
which is not a string, but a symbol(token) and you'll probably end up with an undefined symbol error
saying
'helloworld' doesn't exist unless you define it first. To make this legal you first need to declare the
symbol like this.
int helloworld;
dumb_macro(hello, world) = 3;
printf ("helloworld = %d\n", helloworld); // <-- would print 'helloworld = 3'
##iscalledtokenpassingargumentsinceitisusedtocreatetokensthroughpassed
arguments
Question: Find output of following code snippet in C++
#include <iostream>
#include <conio.h>
using namespace std;
int foo1(){
cout<<"foo1 ";
return 1;
}
int foo2(void* a, void* b){
cout<<"foo2 ";
return 2;
}
int main(){
int x=~foo1()&~foo2(cout<<"a ",cout<<"b ");//foo1 b a foo2
getch();
}
Answer:
foo1 b a foo2
Explanation:<<operatorassociatedwithcoutobjectreturnsareferencetoitselfthis
canbeacceptedbyvoid*(genericpointer)~isnegationoperator.Theoutputdepends
onorderofexecutionofexpressionandorderinwhichparametersarepassedin
function.
Answer: cout is an object to represent standard output stream. << operator associated with it returns
a reference to same standard output stream object. This allows chaining of << operators and thus
cout<<"hello"<<" world";
issameascout<<"helloworld";
Solution:https://github.com/thvdburgt/KnRTheCProgrammingLanguage
Solutions/blob/master/Chapter%205/56/atoi.c
Question: What is fall through? How is it useful?
Answer: Flow of control to following cases after the matching case in absence of break statement after
the matching case is known as fall through.
Fall-through allows multiple labels to be associated with a single action.
Question: What is the significance of break statement after default?
Answer:Fallthroughcanoccurafterdefaulttoo.Ifdefaultisnotthelastlabeland
thereareotherlabelsafteritwithoutanybreakinbetween.Thereforeasadefensive
programmingyoumayaddabreakafterdefaulttooalthoughitislogically
unnecessary.
InQ,20issubstitutedfor*anditindicatesputtingthevalue10in20columns.
Question:WhatistheuseofvolatilekeywordinCLanguage?
BydeclaringavariableasvolatileinCweinstructthecompiler
thatthevalueofthatvariablecanbechangedbymeansoutsidethecodesuchas
hardwareorotherprogram.Itisimportanttonotethatvolatilevariablescanbe
constants(declaredconst)ifthiscodeisnotallowedtochangeitsvalue.Ifwedeclare
avariableasvolatiletheneverytimesuchvariableisencounteredinthecode
compilerfetchesitsvaluefrommemoryinsteadofusinganyoptimizations.This
ensuresthatwearereadingthecorrectvalueofsuchvariable.Volatilememoryaccess
isrequiredincaseoffileswhichcanbereadmymultipleprogramssimultaneously.
Question: What is difference between a character stored in a char variable eg. char ch='x' and a
simple character constant x?
Answer:
Look at the following code
main()
{
char b = 'c';
printf("size of char constant %d\n", (int)sizeof('a'));
printf("size of char variable %d",(int)sizeof(b));
}
Output:
size of char constant 4
size of char constant 1
Explanation:AccordingtotheANSI/ISO99Cstandard,theexpression'a'startswith
typeint.Ifyouhaveafunctionvoidf(int)andavariablecharc,thenf(c)willperform
integralpromotion,butf('a')won'tbecausethetypeof'a'isalreadyint.
Question: What is the significance of value returned by main in C?
Answer: It tells the environment about the status of program execution. 0 signifies normal termination
and non-zero value tells some error in execution. The value returned can be displayed using echo
%errorlevel% in Windows and echo $? in UNIX.
Question: In JAVA main function doesn't return any value so how can you tell the environment
about the status of program execution?
Answer:WecanuseSystem.exit(0);orSystem.exit(<nonzeroerrorcodeas
integer>);
Question: getchar() is a library function to input a character from console. What data type you
should use to store the value returned by this function?
Answer: int !!!
Explanation:EOFisanintegerconstantdefinedinstdio.hwhilereadingcharacters
usinggetchar()EOFisreturnedinsteadofASCIIvalueofthecharacterwhennomore
charactersareavailable.Thereforewemustreadtheinputfromgetchar()inaninteger
andnotchardirectlysothatthevariableisbigenoughtoreadtheEOFvalue.
Explanation:Replacementswon'tbemadewhen<name>occursaspartofother
nameEg.<prefixname>alsoreplacementswon'tbemadeif<name>occursinside
quotes.
Answer: %X.Yf prints a float value right justified in X columns up to 1 digit after decimal. Minus can be
used in format specifier to make the text left justified. Thus the code tells to print 22.44 as 22.4 left
justified in a column whose width is eight.
Question: What are the input and output functions defined in C language?
Answer: There is no input or output function defined in c language. printf & scanf are parts of
standard input output library that is normally accessible to a c program. The behaviour of standard
input output functions are defined in ANSI standard and its properties should be same in any compiler
that follows the standards.
Output:
0
37
37
Explanation:Incautomatictruncationtointegerisdoneforintdatatypevariables.
Onusingfloat/doubleconstantsamecanbepreventedwiththehelpofautomatictype
promotion.
Posted by Abhas Tandon at 10:25 PM No comments:
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
Labels: answers, c, c interview questions, freshers, interview, placements, programming, questions,
technical
In this post you can find 10 Latest c interview questions and answers. These are some of the best c
language questions asked to freshers in technical interviews. I have tried to provide answers with full
explanation. If you are looking for simple c questions then you can have look at my previous posts. You
may ask all your doubts by commenting in the post. I'll try my best to answer your questions at
earliest.
int a=2;
typeof(a) b=1;
printf("%d %d",a,b);//2 1
getch();
int main()
{
int i;
i=5;
change();
i=10;
printf("%d",i); /* this should print 5*/
getch();
}
Answer:
#define printf(x,y) printf("5")
You can use macro to change the default behaviour of library functions as well.
getch();
}
Answer: Size might be 8 and not 5 as expected
Explanation: Size of structure might NOT be sum of size of its elements. It is large enough to hold all
the members. There might be unnamed holes in memory due to alignment requirements.
28
// P
int main() {
printf("%d", sizeof(func(3)));
return 0;
}
Output
2
Explanation:
P: This statement is not executed since fun() is not called.
sizeof is a compile time operator. Operand is evaluated only if it is a variable length array. In above
case all that matters to sizeof is the return type of the function.
int main(){
Answer: Error
Explanation: We cant request address of a register variable. It is illegal to apply & operator to a
variable declared as a register.
Posted by Abhas Tandon at 10:41 PM 2 comments:
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
Labels: answers, c, c interview questions, freshers, interview, programming, questions, technical
#5 Identifier: Names given by programmer to various parts of program. Eg. In int a=5; a is an
identifier.
#6 Token: Smallest individual unit of a program. Eg. variable, constants.
#7 function: Group of statements used to perform a particular task. It may or may not accept
parameters and may or may not return a value. They help in code re-usability.
#8 Keyword: Words which convey special meaning to compiler. Eg. for, int, while etc.
#9 Recursion: When a function calls itself.
#10 Array: Collection of similar data type stored in contiguous memory location.
#11 structure: Collection of data of any data type stored in contiguous memory space.
#12 String: Array of character.
Other simple C language questions asked in mass companies:
#13 Difference between = and == operator
#14 Differences between C and C++
#15 Difference between for(), while and do while loops.
#16 Types of storage class in C (auto, register, extern and static)
#17 Program to reverse a number
#18 C program to swap numbers with and without temporary variable.
#19 Difference between structure and union.
#20 What is typedef.
#21 What is void pointer.
#22 What is null pointer.
#23 Differences between actual parameter and formal parameter.
#24 What is a function definition?
#25 What is a function signature?
#26 Differentiate between call by address and call by value.
#27 Differentiate between switch and if statement.
#28 Difference between malloc() and calloc()
#29 C Program to print factorial of a number.
#30 C Program to find sum of matrix
#31 C sorting programs: bubble, insertion and selection
#32 C code for linear and binary search
#33 What are type casting and type promotion?
Posted by Abhas Tandon at 9:51 PM No comments:
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
Labels: answers, c, c interview questions, freshers, interview, programming, questions, technical
What is a pointer?
Function pointers in C
Function Pointers are variables, which point to the address of a function. A running program
gets a certain space in the main-memory. Both, the executable compiled program code and
the used variables, are put inside this memory. Thus a function in the program code is
nothing more than an address.
Syntax to create function pointers in c
return type (*fnPointer) (arguments-list);
We can assign address of similar function (with same arguments list, return type) by writing
fnPointer=&fnName; // or fnPointer=fnName;
Now we can call the function being pointed as
(*fnPointer)(argument-list);
2
1
01
101
0101
10101
Free download c interview programs as pdf
Free download c interview programs as doc
Most common C Interview questions for beginners
Posted by Abhas Tandon at 12:11 PM No comments:
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
Labels: c, c interview questions, c language, simple c programs
getch();
return 0;
}
continue reading click here for good c interview questions with code and
explanation
more
Check
C
out
Interview
Top
33
interview
Questions
queries
and
related
to
Answers
c
language
}
Answer:
Error in Line number 6. Global variables can have several declarations in C but
only one definition. Same is true for function declarations.
Also check out C interview example programs Questions exercises
You can find more such c interview question in related post mentioned below:
Posted by Abhas Tandon at 8:29 PM No comments:
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
Labels: c, c interview questions, c language
5. Write a program in c language to concatenate two strings without using library functions.
For more c interview question programs etc. click here
Check out more C interview questions in related posts below. In this blog you can also find number of
free pdf which you can download and read later.
C interview basic questions and answers for freshers
Free download c interview programs as pdf
Posted by Abhas Tandon at 8:12 PM No comments:
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
Labels: c, c interview questions, c language
char *s="Abhas";
printf("%s",s+s[1]-s[3]);
getch();
}
Answer:
bhas
Reason/Solution: In the above program role of %s is to display the string whose
address is passed as an argument. This is how a standard printf statement works in
c language. Now since we have passed s- s[1]+ s[3] as an argument therefore first
value of this expression is evaluated. Here s would refer to address of first
character in string s. Since we are subtracting s[1] from s[3] characters at
corresponding position (that are a and b) would be subtracted. On subtracting
a from b (ASCII Value) we get 1 which is added to address of first character in
s (also referred as s). Now printf would get address of second character (address
of first character + 1) as argument so it will display the string starting from second
position.
Hence
output
is
bhas.
Click here to checkout more subjective C Interview question answers
You can see the related posts for more c interview questions answers.
Posted by Abhas Tandon at 7:34 PM No comments:
Email ThisBlogThis!Share to TwitterShare to FacebookShare to Pinterest
Labels: B. Tech, c, c interview questions, interview, interview questions answers