1000 worst ways to do the same thing
#include <iostream>:
using namespace std;
int main(int argc, const char * argv[]) {
cout << "Hello World!";
}
// with a line break:
cout << "Hello World!\n";
// generates the same result:
cout << "Hello World!" << endl;
cout << "First " << "Second " << "Third";
cout << "First" << endl << "Second";
// printing the return-value of a function:
int add(int x) {
return x+x;
}
int main(int argc, const char * argv[]) {
cout << add(2); // 4
}
std::cout << "Enter string:" << endl;
std::string s;
std::getline(std::cin, s);
std::cout << "the string was: " << s << std::endl;
int add(int x) {
return x;
}
int add(int x, int y) {
return x+y;
}
// this won't work:
int add(int x, y) {
return x+y;
}
int add(int x) {
cout << "int function";
return x+x;
}
double add(double x) {
cout << "double function";
return x+x;
}
int main(int argc, const char * argv[]) {
cout << add(2.5); // double function
cout << add(2); // int function
}
int add (int a, int b) {
return a + b;
}
int useFn(int a, int b, function<int(int, int)> fn) {
return fn(a, b);
}
int main() {
cout << useFn(2, 3, &add) << endl;
}
void PrintValue(int value) {
cout << "Value: " << value << endl;
}
void ForEach(
const vector<int> &values, void (*func)(int)
) {
for (int value : values) {
func(value);
}
}
int main() {
vector<int> values = {1, 2, 3, 4, 5};
ForEach(values, PrintValue);
return 0;
}
auto lambda = []() { cout << "Hi" << endl; };
lambda();
int a = 5;
auto lambda = [a]() { cout << "Hi" << endl; };
lambda();
int numbers[] = {1, 2, 3, 4, 5};
// alternatively:
int numbers[2];
numbers[0] = 1;
numbers[1] = 2;
int numberes[5];
for (int i = 0; i < 5; i++)
numbers[i] = 2;
int numbers[5];
int* ptr = numbers;
numbers[2] = 5;
// value change:
*(ptr + 2) = 6;
// printing 6
cout << numbers[2] << endl;
int* anotherArray = new int[5];
delete[] anotherArray;
int a[5];
int count = sizeof(a) / sizeof(int);
int *returnArr() {
int coordinates[2] = {1, 2};
return coordinates;
}
int main() {
int x = returnArr()[0];
}
void multiply(int nums[3]) {
for (int i = 0; i < 3; i++) {
cout << nums[i] * 2 << endl;
}
}
int main() {
int nums[3] = {1, 2, 3};
multiply(nums);
return 0;
}
int number = 420;
int numberPointer = *number;