Int in C++
int n;
if n in global scope n=0 otherwise undetermined
int a, b; ✅
int a=b=0 ❌
Compile Error ❌
int func; // Variable declarationvoid func() {} // Function declarationyou cannot declare a function and a variable with the same name in the same scope, but you could declare them in different scope. This is because it would create ambiguity for the compiler
Convert char to its ASCII value:
char ch = 'C';int a = int(ch); ✅// Explicit conversion, ASCII value of 'C' is 67int b = ch; //✅ Implicit conversion, also results in 67Convert char to its numerical value (‘1’ to 1):
char ch = '5';int a = ch - '0'; // '5' - '0' = 5-0;// Ascii Value of 5 - Ascii Value of 0 = 5Read a whole line (even if include whitespace)
#include iostreamstd::string str;std::getline(std::cin, str);int a=1;
if(a) cout<<1, a++; ✅if(a) cout<<1, return 1; ❌Note: comma operator allows two or more expressions to be executed sequentially, but return is a control statement, not an expression, so it cannot be used in this way.
bool with Arithmetic Operations in C++
bool a = true, b = false, c = 3, d = 0;int e = 1;int sum = a + b + c + d + e; // 1 + 0 + 1 + 0 + 1 = 3boolbehaves like integers (0or1) in arithmetic.- Any non-zero assigned to
boolbecomestrue(i.e., 1). - In expressions,
boolvalues are added likeint.
Cpp Invalid Variable Declaration
int a, b, c = 0, 1, 2; // ❌ Only 'c' initialized to 2, rest are undeclaredint a = 0, int b = 1, int c = 2; // ❌ Wrong syntaxCpp valid Variable Declaration
int a = 0, b = 1, c = 2; // ✅ Preferred: single-line declarationint a = 0; int b = 1; int c = 2; // ✅ Valid but less clean- In C++, type is specified once per declaration line.
int a, b = 0, 1;means onlybis initialized with 1;ais uninitialized.- Unlike Python/JS, C++ doesn’t support unpacking style (
a, b, c = 0, 1, 2).