What will be the result of the following program?
main()
{
char p[]="String";
int x=0;
if(p=="String")
{
printf("Pass 1");
if(p[sizeof(p)-2]=='g')
printf("Pass 2");
else
printf("Fail 2");
}
else
{
printf("Fail 1");
if(p[sizeof(p)-2]=='g')
printf("Pass 2");
else
printf("Fail 2");
}
}
a) Pass 1, Pass 2
b) Fail 1, Fail 2
c) Pass 1, Fail 2
d) Fail 1, Pass 2
e) syntax error during compilation
Answer Posted / jaroosh
Fail 1 , Pass 2.
Some explanation,
1. Fail 1
first of all, to compare strings in C, you use this strcmp
function, so this WOULD give PASS 1 :
if(strcmp(p,"String") == 0)
but
if(p=="String")
will fail because this line means :
if address of p is the same as address of some temporary
storage for literals, where literal "String" is stored,
which is very rarely true, because storing literals is
compiler specific and is very hard to estimate at runtime.
2. Pass 2
sizeof(p) gives 7, because sizeof(char) is 1 byte, and we
have 7 chars in array storing "String", which are :
[0]S
[1]t
[2]r
[3]i
[4]n
[5]g
[6]\0 (EOS)
now, clearly sizeof(p) - 2 is [5] which is "g"
thats why
if(p[sizeof(p)-2]=='g')
is true.
| Is This Answer Correct ? | 10 Yes | 0 No |
Post New Answer View All Answers
What is a built-in function in C?
What is a stream?
When a c file is executed there are many files that are automatically opened what are they files?
Can you think of a logic behind the game minesweeper.
Why is c platform dependent?
What does %p mean?
Here is a good puzzle: how do you write a program which produces its own source code as output?
c programs are converted into machine language with the help of a) an interpreter b) a compiler c) an operatinf system d) none of the above
How do I copy files?
Is linux written in c?
What is n in c?
What is meant by realloc()?
What is floating point constants?
what is event driven software and what is procedural driven software?
In C language, the variables NAME, name, and Name are all the same. TRUE or FALSE?