Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code working in c but not in c++

Tags:

c++

c

The following code is working fine in C but when I try to write it in c++ then the program does not work.Please explain.

C code :

#include<stdio.h>
#include<stdlib.h>

int main()
{
    int a = 33,b = 7;
    printf("%d\n",a&b);
    return 0;
}

C++ code:

#include<iostream>

using namespace std;

int main()
{
    int a = 33,b = 7;
    cout << 33&7 << endl;
    return 0;
}
like image 540
Devender Goyal Avatar asked Nov 27 '22 03:11

Devender Goyal


2 Answers

Watch your operator precedence:

cout << (33 & 7) << endl;

& has lower precedence than <<. So you need to use ().


For the full list of operator precedence in C and C++:

http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence

like image 102
Mysticial Avatar answered Jan 07 '23 05:01

Mysticial


This question nothing has nothing to do with the difference between C and C++. This is about the precedence of the operators and deciding where the borders of the expression are. The right example should look like:

printf("%d\n", a&b);

and

short cout;
int endl;
long var = cout << 33 & 7 << endl;

The fact, that C++ I/O advises to use << for printing variables is not important. C++ says that the precedence of the overloaded ops is the same as the precedence of regular operators.

like image 26
Kirill Kobelev Avatar answered Jan 07 '23 04:01

Kirill Kobelev