The greatest mistake you can make in life is to be continually fearing you will make one

Wednesday, 3 March 2010

C Question of the Day -Preprocessor2

1.What will be printed on the screen?
#include<stdio.h>
#define x -100
int main()
{
    int x;
    #ifdef x
        printf("Hello friend\n");
    #else
        printf("Hello enemy\n");
    #endif
    return 0;
}
  1. Hello friend
  2. Hello enemy
  3. Compiler error
  4. Hello friend Hello enemy
Solution
Compiler error
The preprocessor replace int x; as int -100; so the compiler produce expected identifier error. If the statement int x; is not there then the output is Hello friend


2.What is the output of the following program?
#include<stdio.h>
#define ZERO 0
int main()
{
    #ifdef ZERO
        printf("Zero defined\n");
    #endif
    #ifndef ZERO
        printf("Zero undefined\n");
    #endif
    return 0;
}
Solution
Zero defined

3.What is the output of the following program?
#include<stdio.h>
#define ADD(X,Y) X+Y
int main()
{
    #undef ADD
    fun();
    return 0;
}
void fun()
{
    #ifndef ADD
        #define ADD(X,Y) X*Y
    #endif
    int z=ADD(3,2);
    printf("z=%d",z);
}
Solution
z=6

4.What is the output of the folowing program?
#include<stdio.h>
#define ADD(X,Y) X+Y
int main()
{
    #undef ADD
    fun();
    return 0;
}
void fun()
{
    #ifndef ADD
        #define ADD(X+Y) X*Y
    #endif
    int z=ADD(3,2);
    printf("z=%d",z);
}
 Solution
Compier error: "+" may not appear in macro parameter list

 5.What is the output of the following program?
#include<stdio.h>
#ifdef TRUE
    int X=0;
#endif
int main()
{
    int Y=1,Z=2;
    printf("X=%d,Y=%d,Z=%d\n",X,Y,Z);
    return 0;
}
Solution
Compier error: X undecared


6.What is the output of the folowing program?
#include<stdio.h>
#undef _FILE_
    #define _FILE_ "WELCOME"
int main()
{
    int Y=1,Z=2;
    printf("%s\n",_FILE_);
    return 0;
}
  1. Compilation Error
  2. Run Time Error
  3. Compiles But gives a warning
  4. Compiles Normally
Solution
4.Compies Normally.
The program compiles without error and produce output as WELCOME

7.What is the output of the following program?
#include<stdio.h>
#pragma pack(2)
struct SIZE
{
    int i;
    char ch;
    double db;
};
int main()
{
    printf("size=%d\n",sizeof(struct SIZE));
    return 0;
}
  1. 12
  2. 14
  3. 16
  4. 8
Solution

2.14
size of int 4 bytes,char 1 byte and doube 8 bytes. each member alignment take 1 byte.integer is packed to 2 bytes. so 14 bytes.
#pragma pack(2) directive would cause that member to be packed in the structure on a 2-byte boundary.If #pragma pack(2) line is not there then the output is 16.and if #pragma pack(4) is there then there is no effect.and output is same as original 16

8.What is the output of the following program?
#include<stdio.h>
#if something==0
    int some=0;
#endif
int main()
{
    int thing=0;
    printf("some=%d,thing=%d\n",some,thing);
    return 0;
}
Solution


some=0 thing=0

No comments:

Post a Comment