- Parenthesize each of the following
expressions fully, to show how they are evaluated in C. Hint: You do not need
to know what the operators do to answer this problem.
a = b * c == 2
a = b && a > z ? x = y : z
a = s . f + x . y
a = b >> 2 + 4
c = getchar() == EOF
- The following fragment of code will produce a segmentation fault
since it tries to access memory using a NULL pointer:
int *p;
p = NULL;
if (*p == 13)
printf(" got it!\n");
Will the following fragment of code also produce a segmentation fault? Why or
why not?
int *p;
p = NULL;
if (p != NULL && *p == 13)
printf("got it!\n");
- Use the following code fragment to answer the questions below:
i = 2;
switch(i){
case 1: printf("moo\n");
case 2: printf("baa\n");
case 3: printf("meep\n");
case 4: printf("sproing\n");
}
- What is the output of the above switch statement?
- What is the output if i were set to 3 rather than 2 in the first
statement?
- What is the output if i were set to 0 rather than 2 in the first
statement?
- Rewrite the following program without using break, continue,
or goto.
/* Count the number of a's */
/* in a line given as input */
#include <stdio.h>
#include <ctype.h>
void main(void)
{
int num_a = 0;
int c;
c = getchar();
while(1) {
if (c == '\n')
break;
if (isdigit(c))
continue;
if (c == 'a')
goto add_num_a;
get_next_char:
c = getchar();
goto end_loop;
add_num_a:
num_a++;
goto get_next_char;
end_loop:
;
}
printf("%d\n", num_a);
exit(0);
}
- What does the following segment of code print?
char *c[] = {
"ENTER",
"NEW",
"POINT",
"FIRST"
};
char **cp[] = { c+3, c+2, c+1, c };
char ***cpp = cp;
main()
{
printf("%s", **++cpp );
printf("%s ", *--*++cpp+3 );
printf("%s", *cpp[-2]+3 );
printf("%s\n", cpp[-1][-1]+1 );
}
Hint:
Draw a picture of the arrays and the pointers.
- Here is a macro for computing the minimum of two numbers:
#define min(a, b) ((a) > (b) ? (b) : (a))
and here is a function:
int min(int a, int b)
{
return(a > b ? b : a);
}
In
the following code fragment, give the values of a, b,
c, d, and e at the end if min is the above
macro, and then if min is a function call:
a = 2;
b = 3;
c = 4;
d = min(++a, b);
e = min(c++, b);