Skip to content

Instantly share code, notes, and snippets.

View gpetuhov's full-sized avatar
💭
Working on a project

Gennadiy Petuhov gpetuhov

💭
Working on a project
View GitHub Profile
@gpetuhov
gpetuhov / dynamic_array.cpp
Last active March 17, 2017 10:15
C++ Dynamic array
int n = 0; // Number of elements in array
int* arr;
cout << "Enter number of elements in array" << endl;
cin >> n;
arr = new int[n];
for (int i = 0; i < n; i++) {
*(arr+i) = i;
cout << *(arr+i) << " ";
}
cout << endl;
@gpetuhov
gpetuhov / pass_value_reference.cpp
Created March 17, 2017 10:40
C++ Pass by value and pass by reference
// Arguments are passed by value.
// swap1 will swap x and y, not the variables that are passed into it.
void swap1(int x , int y) {
int temp;
temp = x;
x = y;
y = temp;
}
// swap2 takes pointers as arguments, so it will swap the initial variables
@gpetuhov
gpetuhov / static.cpp
Created March 17, 2017 11:00
C++ Static variables
// Argument is passed by reference, so the initial variable changes
int f(int &x) {
// Static variable is created only once
// and is not destroyed after function is finished.
static int a = 0;
if (!a) a = ++x; // !a is true only if a = 0
return a;
}
int main() {
@gpetuhov
gpetuhov / references.cpp
Created March 17, 2017 11:01
C++ References
// x1 is passed by value, initial variable doesn't change
// x2 is passed by reference, initial variable changes
int f1(int x1, int &x2) {
return ++x1 + (++x2);
}
int main() {
int x=39, *p = &x;
cout << p << " " << *p << endl;
// Result is address of x and value of x (39)
@gpetuhov
gpetuhov / friend.cpp
Created March 17, 2017 11:10
C++ Friend example
class A
{
friend int Freund(); // function Freud() will have access to A's private fields
friend class B; // class B will have access to A's private fields
public : int x, y;
private : short i;
} A1;
class B
{
@gpetuhov
gpetuhov / include.cpp
Created March 17, 2017 11:25
C++ Include example
// file hello.cpp
#include <cstdlib>
#include <iostream>
using namespace std;
void HelloWorld() {
cout << "Hello, world!" << endl;
}
@gpetuhov
gpetuhov / namespace.cpp
Created March 17, 2017 11:31
C++ Namespaces
#include <iostream>
using namespace std;
int m = 5;
namespace space1
{
int x1 = 3;
namespace space2
{
@gpetuhov
gpetuhov / exception.cpp
Created March 17, 2017 11:42
C++ Exception
short x = 4, i = 0;
void fun1()
{
if (i == 5) throw 2;
}
void fun2()
{
--x;
@gpetuhov
gpetuhov / hex.cpp
Created March 17, 2017 11:44
C++ Output in hex
int x = 15;
cout << hex << x << endl;
@gpetuhov
gpetuhov / file.cpp
Created March 17, 2017 11:48
C++ File
FILE* textFile;
textFile = fopen("file.txt", "w");
for (int i = 0; i < 10; i++) {
fputs("1 ", textFile);
}
fclose(textFile);