- What is the output of the following program?
CPP
#include <iostream> using std::cout;
int main()
{ int i = 0;
cout << (i = 0 ? 1 : 2 ? 3 : 4);
return 0;
} |
- a. 1
b. 2
c. 3
d. 4
e. compile error
Answer : C
Explanation: Ternary operator is right to left associative. So the expression becomes (i = 0 ? 1 : (2 ? 3 : 4)) which evaluates as (i = 0 ? 1 : 3). Note the expression “i = 0” assigns 0 to i and returns 0. So 3 is returned and printed. - What is the output of the following program?
CPP
#include <iostream> int main()
{ printf ( "%.3lf" , sizeof "Geeks" / sizeof "forGeeks" );
return 0;
} |
- a. 0.000
b. 1.000
c. 0.667
d. Compile error
Answer : a
Explanation: The operator sizeof returns an integer and not a double. In case of strings it returns the length of the string including the \0. The sizeof of “Geeks” is 6, and the sizeof the string “forGeeks” is 9. In terms of integers, 6/9 is equal to 0. - What is the output of the following program?
CPP
#include <iostream> using std::cout;
int main()
{ cout << 5 [ "GeeksforGeeks" ];
return 0;
} |
- a. Geeks
b. f
c. forGeeks
d. compile error
Answer : b. Explanation: In C/C++, the statement X[Y] is identical to *(X+Y). In this case the statement is equal to *(5+"GeeksforGeeks"). The + operator is commutative, so we can write the expression as *("GeeksforGeeks"+5). This statement means 5th character of the string from the beginning of the string. So finally we print f.
- What is the output of the following program?
CPP
#include <iostream> using std::cout;
int main()
{ int i = 0, j = 0;
++++j = ++++i + i++;
cout << i;
cout << j;
return 0;
} |
- a. 12 b. 34 c. 22 d. compile dependent
Answer : d Since ++ operator does not define a sequence point, applying it multiple times on same variable in an expression causes undefined behavior.
- What is the output of the following program?
CPP
#include <iostream> using std::cout;
int main()
{ int i = 0, j = 0, k;
i++;
j++ ++;
k = (i++) + j;
cout << i;
cout << j;
cout << k;
return 0;
} |
- a. 123 b. 124 c. 224 d. Compile Error Answer is: d. Explanation: Unlike ++++j, the statement j++ ++; is illegal.
Article Tags :
Recommended Articles