There are several ways to do this, below are some of the most popular ones:
• if(printf("Hello, World!\n")) { }
• while(!printf("Hello, World!\n")) { }
• switch(printf("Hello, World!\n")) { }
How to swap two numbers without using temporary variable ?
This one would figure in anyone's list of elite questions in Orkut programming communities that are guaranteed a minimum of 50 responses everytime someone raises it, if at all anyone were to be jobless enough to compile one such list. This question is often asked in many interviews in India and so obviously many would be interested in knowing the answer.
And it would come as a rude jolt to many when confronted and told that there is no standard conformant way of doing this which would apply equally well to all built-in types.
I would like to discuss all the solutions that have been offered so far.
a=a+b;
b=a-b;
a=a-b;
The above method wont work because it doesn't take into account overflow errors. Suppose for example if we had to swap two signed numbers 1 and 32767 on a system where int is 16 bits long. On such a system, the maximum value an int can store (INT_MAX) would typically be 32767.
So when the first step a+b is executed the result would be 32768, which would be larger than the maximum value that can be stored in an int variable. Consequently this value cant be stored in a and hence an overflow occurs. What happens after this is undefined. No matter what happens under the hood, the result is bound to be undefined and hence this method fails whenever an overflow occurs.
a=a*b;
b=a/b;
a=a/b;
This method would fail for the same reason the previous code snippet would fail. Here a*b can overflow. This has more problems as well. a/b can overflow too. This method would also fail if b were zero, as it would cause divide by zero error. So this is another worthless suggestion.
a=a^b;
b=b^a;
a=a^b;
The method above wont work for floating point values. Bitwise operators are not defined for floating points and hence this solution can be used only when the numbers to be swapped are not floating points. Usage of this method on variables other than int (char, long, short) would result in Undefined Behavior(UB). In all the three methods above, the compiler implicitly uses temporary values to store the result from the mathematical operations and this temporary value is then copied into the l-value. So technically we are using temporary values here too. But let us proceed assuming that the question here is to swap two variables without defining any temporary variable in the user code.
a^=b^=a^=b;
a=a+b-b=a;
The two code snippets shown above impresses almost every newbie the first time they see it. They would leave no stone unturned in praising the author of this code. Little do they realize that this code is not guaranteed to produce the same result on every system they test it on.
Here we are entering the realm of Undefined Behavior often abbreviated as UB.
There are three kinds of operators: unary, binary and ternary. Unary operators are those which operate on one and only one operand. Unary+, Unary-,dereferencing operator* are some examples. Binary operators are those which operate on two operands. Addition (+), Subtraction (-), Logical Or (||) are a few examples of binary operators. There is only one ternary operator in C++ viz ?:.
When the compiler sees an expression, it breaks them into smaller units depending on a table called the operator precedence table∞. The operators at the top of the table are the ones executed first followed by other operators in the decreasing order of precedence.
Now each of these operators can operate on one, two or three operands. These operands can themselves be expressions.
For example : int a=(b+c)*(d+e);
Here the operator * has two operands. The former is a simple expression (b+c) and the latter is another simple expression (d+e).
Now the C++ standard doesn't place any condition on the order in which these expressions must be evaluated. A normal human being would first calculate (b+c) and store it in a temporary variable. He would then calculate (d+e) and store it in another temporary variable. He would then retrieve these two temporary values and then multiply them and store the result in the variable a. But the standard lays down no such conditions or rules. It leaves the choice to the compilers. So the compilers can evaluate either (d+e) first or (b+c) first. Different compilers choose to do it differently.
For the simple expression given above this doesn't cause much confusion. The reader would probably be wondering as to why I am rambling on about it when evaluating (b+c) or (d+e) first doesn't change the result.
Surprise!!!
Consider this expression:
int i=1;
int temp=i++*(i-1);
Here the operands of the multiplicative operator * are i++ and i-1;
Now as mentioned before the compiler can evaluate either i++ first or (i-1) first. Let us see what happens when i++ is evaluated first. After i++ is evaluated the value that would be returned would be the existing value i.e. 1 and i would now be 2. After this i-1 is evaluated which would be 1. So i++*(i-1) would be 1*1 which is equal to 1. So temp would be 1 now.
Now let us see what happens when (i-1) is evaluated first. Since i is 1, i-1 becomes zero. Irrespective of what i++ is now, i++*(i-1) would be zero. So temp is initialized to zero here.
Do you realize the mistake? The result here depends on the order of evaluation and hence is unpredictable. It is unreasonable to expect all compilers to follow the same order of evaluation. Hence temp will be initialized to 1 on some systems and it will be initialized to zero on some other systems. This is Undefined Behavior and it is more often than not better to avoid coding practices like these.
Now this brings me to the discussion of sequence points. I have tried hard and exhausted myself in the process of trying to convince people that they should pay special attention to this topic. Please check C-faq∞ and Wikipedia article∞ for more info on sequence points.
After reading those topics some users confuse themselves between operator precedence and sequence points. Sequence points has got nothing to do with operator precedence. This requires more explanation.
When a compiler sees an expression with many operators, it breaks the expression into many logical and simpler units. How it does this depends on operator precedence.
For example when the compiler sees an expression like a+b*c+d, here the two operands are binary multiplicative operator * and binary addition operator +. * has higher precedence.
So the first step would be to choose * as the point where the expression can be split into simpler units. So the expression would now become a+(b*c)+d.
This expression is evaluated from left to right as + has left to right associativity. So the expression would become ( a + (b*c) ) + d
Now assuming a and d are simple expressions themselves. In this case consider the first binary addition operator.
Its operands are d and ( a + (b*c) ). Now as I mentioned before, the compiler can evaluate either d first or it can evaluate ( a + (b*c) ) first.
Now if it chooses to evaluate ( a+ (b*c) ) first, it can further choose to evaluate (b*c) first or a first. And further if b and c were expressions themselves, then we cant be sure about which amongst b or c would be evaluated first. The standard doesn't guarantee much here.
So the expression a+b*c+d which appears so simple to the naked eye has so many complications when we enter the realm of compilers and it is always better not to assume anything.
Hope that clears things a bit.
Now coming back to the original discussion. Why do those two code snippets lead to UB?
For precisely the same reason (i++)*(i-1) leads to UB. In the first code snippet there are many XOR operations operating on the two variables a and b. The author of the code ends up modifying the variables a and b more than once between two sequence points which results in UB.
In the second code snippet, the author assumes that b=a would be evaluated first before all other expressions. It may or may not be evaluated first. The results would be different for both the cases and hence leads to be UB again.
Now to summarize, there is no known way to swap two variables without using a third variable that would apply equally well to all built-in types.
Below is one more way to add two numbers without the arithmetic operators. This method makes use of the asterisk(*) field width specifier in the printf function and use the returned value from printf. Here the printf statement is given with field width operator in format, and the two numbers are given as argument for field widths, hence we are printing a total width of two given integer arguments. The printf function returns the number of characters printed, and here the total number of characters printed will be sum of a and b. The third and fifth arguments are zero length strings because it only needs to print the total width of two integers.
Note that this method only works for unsigned integers.
unsigned add(unsigned a, unsigned b)
{
return printf("%*s%*s", a, "", b,"");
}
How to find whether a given number is even or odd without using % (modulus) operator ?
A newbie question. Here is a simple C++ solution.
bool isOdd(int num){
return num&1?true:false;
}
If the number is odd then it's least significant bit (LSB) is set i.e. it is 1. If it is even then it is 0. When you bitwise and (&) this number with 1, the result would be either 1 if the number is odd or zero if it is even.
As rightly pointed out by SpS, the same code can be implemented in C (following C99 standard) as
#include
bool isOdd(int num){
return (num&1)?true:false;
}
Here stdbool.h defines the macros bool, true and false. The macro bool is defined to be _Bool (the boolean type according to C99 standard). true is a macro which expands to the decimal constant 1 and false is a macro which expands to decimal constant 0.
For C89 sticklers
int isOdd(int num){
return (num&1);
How to find whether the given number is a power of 2 in single a single step (without using loops) ?
Ok this is another often repeated question. But unlike the others, this has a legitimate solution.
Before I show you the code for this, I would like to explain a few things first. We are required to find if a number is a power of 2 in just one step. A number would be a power of two if there is exactly one bit that is equal to 1 in its bit pattern (even 1 is a power of 2. 2 raised to the power zero is 1). Now we could use the method that we used to count the number of bits that are 1 in a given number and check if it is equal to 1. However that approach needs many steps and hence wont suffice here.
In a number which is an exact power of 2 only 1 bit is set and all others are zero. Let the position of this 1 bit be MSB. Mathematics rules for binary numbers tells us that if we subtract 1 from this number then the number that we would get would have all its bit starting from the bit position MSB+1 set to 1. For example if the given number num is 8(00001000) then num-1 would be 7 (00000111). Now we notice that these two bit patterns dont have a 1 in the same bit position. Further observation suggests that if we bitwise and (&) both these numbers we would get zero.
It can also be proved that num&(num-1) would be zero only if num is a power of 2. I leave that as an exercise. If you are'nt able to figure out why it is so, then just leave a comment here and I will explain that part too.
Now here is the code:
bool isPowerOf2(int num){
return ((num>0) && (num & (num-1))==0);
}
How to find greatest of two/three/four numbers without using relational operators ?
Finding greatest of two numbers:
• int maxof2(int a,int b)
{
return (a + b + abs(a - b))/2;
}
• /****************************************************
Purpuse : Evaluate the bigger one of two integers.
Author : ALNG
Date : 2003-03-11
Original : http://search.csdn.net/Expert/topic/1515/1515035.xml
**************************************************/
inline int signof(int i)
{
return unsigned(i) >> (sizeof (int) * 8 - 1);
}
int max(int a, int b)
{
int p[2];
p[0] = a;
p[1] = b;
return p[signof(a - b)];
}
Function for finding greatest of three numbers:
int maxof3(int a, int b, int c)
{
return (a + b + c * 2 + abs(a - b) + abs(a + b - c * 2 + abs(a - b))) / 4;
}
Function for finding greatest of four numbers:
int maxof4(int a, int b, int c, int d)
{
return (a + b + c + d + abs (b - a) + abs(d - c) + abs(a + b - c - d + abs( b - a) - abs(d - c)))/ 4;
}
How to print 1 to n(a user defined value) without using any kind of loops or recursion ?
This is is very easy to implement in C++ using a constructor and a static member to count the number of objects instantiated of that class as shown in the below code:
C++
#include
class a{
public:
a(){std::cout<<++i<
static int i;
};
int a::i; //allocates memory for the static variable
int main(){
int n=0;
std::cout<<"Enter the maximum number that you want to print: ";
std::cin>>n;
a* array=new a[n]; //this statement prints 1 to n because creating an array of n objects calls the default class constructor n times
return 0;
}
Note: This does use implicit loop when objects are created, but there aren't any explicit looping statements or recursion in the program.
For C language, we can do this using setjmp and longjmp as given in the below code. Again there is an implicit loop, but no explicit looping construct or recursion used.
#include
#include
static jmp_buf jmpbuf;
static int val = 1, n;
void printvalue(void)
{
printf("%d\n",val++);
longjmp(jmpbuf,val);
}
int main()
{
printf("Enter the N value:");
scanf("%d",&n);
if (setjmp(jmpbuf) > n)
return 0;
else
printvalue();
}
What is wrong with using void main()? Where does the returned value from main() go?
The main() function has to return an integer value which indicates the exit status of the program. The C and C++ standards only allow declarations for main function in the below forms:
• int main(void) { /* ... */ }
• int main(int argc, char *argv[ ]) { /* ... */ }
Or any other form which is equivalent of the above two, such as int main() and int main(int argc, char **argv).
Program to print its own source code as output
A Program which reproduces its own source code is called as a quine.
There are lots of ways to do this, here are some of them:
• main(){char *c="main(){char *c=%c%s%c;printf(c,34,c,34);}";printf(c,34,c,34);}
• main(){char*a="main(){char*a=%c%s%c;int b='%c';printf(a,b,a,b,b);}";int b='"';printf(a,b,a,b,b);}
What are the differences between C and C++ ?
Can you write a code which compiles in C but not in C++ ?
This question puzzles many who believe that C++ is a superset of C language, and all C language code is valid in C++. But it is not true and you should read the differences between C and C++ to know how they are different.
Below are few examples which compiles in C and would fail to compile in C++:
Example 1:
#include
int main()
{
int class;
class=10;
printf("%d",class);
}
This will not compile under C++ because class is a keyword, but will compile in C without any problems. Similarly any keywords which are specific to C++ such as public, private, virtual, friend etc can be used as identifiers in C, but not in C++.
Example 2:
int fun()
{
//some code
}
int main()
{
fun(10,20);
}
This will fail to compile in C++, because in C++, the declaration of a function with no argument list is equivalent to declaring it as function with void parameter list. But in C language, it means a function with unspecified number of arguments and we can pass any number of arguments to this function in C.
Example 3:
#include
int main()
{
int *array=malloc(sizeof(int)*100);
}
This is valid in C because a pointer of type void* can be assigned to any other pointer without cast, but this is not in valid C++ because will have to give an explicit cast to it as in:
int *array=(int*)malloc(sizeof(int)*100);
Example 4:
#include
int main()
{
static int i=5;
if(i>0)
printf("%d\n",i);
else
{
i--;
main();
return 0;
}
}
What are far, huge and near qualified pointers?
What are far, huge and near qualified pointers?
How to count the number of 1's (set bits) in a given number ?
This is another question that confounds most of the newbies in Orkut and they end up confusing themselves and the others.
There are many ways you can do this, below are a few naive methods for the beginners:
int countBits(unsigned num){
int count= 0;
while(num){
count += num & 1;
num >>= 1;
}
return count;
}
int countBits(unsigned num){
for(unsigned int count=0; num; count++){
num&=num-1;
}
return count;
}
Here is how you can do it in C++ using the bitset class provided in the STL.
int countBits(int num){
std::bitset
return temp.count();
}
What are wild and dangling pointers?
A pointer which is not initialized with any address is called as a wild pointer. It may contain any garbage address, so dereferencing a wild pointer is dangerous(as it causes undefined behavior). A dangling pointer is a pointer which no longer points to any valid location. It is just as dangerous as wild pointer as it contains invalid location.
Example:
#include
int main()
{
int *p; /*At this point, the pointer p is a wild pointer. Its uninitialized, so it may have any random address in it*/
p=malloc(sizeof(int)*10); /* p is initialized with the address to an array of 10 integers */
free(p); /* p becomes dangling pointer as it no longer points to a valid location. */
p=NULL; /* p is no longer dangling pointer as it now initialized with NULL*/
}
How can we return more than one value from a function?
One simple way is to embed the different values that we want to return in a struct and then return the struct.
Example:
struct data
{
int a;
float b;
}
struct data myFunction(void)
{
struct data x;
/*set values for the members of x*/
return x;
}
int main()
{
struct data myData;
myData=myFunction();
/*Now you can access the different values within myData structure*/
return 0;
}
The other way around is to pass the pointers to different objects as argument to the function.
Suppose, you need a function fun1() to return one integer value and three float values, then, declare fun1() as:
int fun1(float *x, float *y, float *z);
Example:
int fun1(float *x, float *y, float *z)
{
int status;
/*Set the values of *x, *y, *z and status*/
return status;
}
While calling the function, pass address of three float variables in which you want to store the returned values, like:
x = fun1(&float1, &float2, &float3);
No comments:
Post a Comment