quinta-feira, 16 de novembro de 2017

Simples encadeamento de operadores '<<'

// O operador >> pode ser usado de forma encadeada.

#include <iostream>
using namespace std;

int main(void)
{
  char nome[80];

  cout << "Qual o seu nome?";
  cin >> nome;
  cout << "Ola" << " " << nome << ", tudo bem?"; // encadeamento do operador '<<'
  cout << "Como voce esta?";
  cout << "Desejo-lhe uma excelente semana!";

}

terça-feira, 14 de novembro de 2017

Alocar/desalocar memória e zerar o ponteiro.

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
int x = 20;    // Aloca memória
int* px;

px = &x;  // & para acessar o endereço de memória da variável x
cout << *px << endl;
delete px;  // Desaloca memória
px = NULL// Zera o ponteiro

return 0;

}

-----------------------------------Com Array--------------------------------------

#include <iostream>
using namespace std;

int main(int argc, char *argv[])
{
    int* ponteiro = new int[10];   // aloca memoria
    cout << "Digite um numero: ";
    cin >> *(ponteiro);
    cout << "Voce digitou: " << *(ponteiro) << endl;
    delete[] ponteiro;     // desaloca memoria
    ponteiro = NULL;   // zerando o ponteiro

    return 0;
}

quinta-feira, 9 de novembro de 2017

Ponteiros



É uma variável que contém o endereço de outra variável na memória interna do pc.

#include <iostream> // Entrada e saída de dados
using namespace std; // Declarando espaço de nome std padrão
int main(int argc, char *argv[])
{
   int var = 10;
   int* pvar; // Ponteiro
   // Sempre inicializar um ponteiro antes de utilizá-lo

   pvar = &var; // &var é o endereço da variável var
   cout << *pvar << endl;//acessa o conteúdo da variável através do *pvar
   *pvar = 20; // muda o valor da variável através do ponteiro

   cout << var << endl;
   
   return 0;
}


quinta-feira, 26 de outubro de 2017

Funções


São fragmentos de código que executam uma tarefa específica,determinada e que pode ser utilizada
em vários caminhos diferentes. Pode ser chamada diversas vezes em um mesmo programa.
São utilizadas para otimizar o tempo e agregar valores de direção padrão, sem que haja a necessidade de repetir o processo de elaboração.

Definição da função:

<tipo de função> nome da função( declaração dos parâmetros) // cabeçalho da função
{
  // escopo da função
  <declaração das variáveis locais>   
                                       
  Comandos que formam o corpo da função
                                       
return <valor>; // ou return; ou nada   

}

Tipos de funções:

void
int
float
double
char
struct
...

Segue abaixo, um exemplo simples de manipulação com funções:

/*
Function name: main, bool
Objective: Show how to handle functions.
return: 0
*/
#include <iostream>
#include <cstdlib>
using namespace std;

bool even(int num);
void message();
int main()
{
    int n;
    message();
    cout << "Enter number: ";
    cin >> n;
    if(even(n))
    {
        cout << "The number " << n << " is even." << endl;
    }
else
    {
    cout << "The number " << n << " is odd." << endl;
    }
    system("pause");
    return 0;
}
void message()
{
    cout << "learning C++ with fun!" << endl;
}
bool even(int num)
{
    if(num % 2 == 0)
        return true;
    return false;
}

P.S:
1- O Visual Studio Code é o editor que utilizo.  É uma Plataforma aberta, tem ferramentas de  identificação de código e de integração com o Github. Poxa, o esquema de cores é, de fato, encantador. Sem falar que suporta as principais linguagens de programação com a sintaxe e até direito a preenchimento automático! Nhamy!  
2-  O exemplo acima  saiu  muito irreverente, com espaçamentos maiores do que o que parece belo. Eu copiei e colei do meu editor para obter uma representação quase fiel(quase mesmo) dele.  

segunda-feira, 23 de outubro de 2017

Makefile para windows/(Makefile for windows)

Para a simplificação e aceleração na compilação de programas, utilizo do Makefile(arquivo de configuração usado pelo programa Make). Maneira fácil de compilar, visto que o programa Make é opensource e existem versões para sistemas operacionais diferentes.
O Make é "LIKE A BOSS"!

Você deve estar se perguntando: Como instalar e usar o "Make" no Windows?

Primeiro, você deve instalar o MinGW:
https://sourceforge.net/projects/mingw-w64/

Depois, você abre o console, e no diretório "c:" você copia da forma que está abaixo:

copy c:\MinGW\bin\mingw32-make.exe c:\MinGW\bin\make.exe

Agora, é só executar o comando make.exe no seu console no windows.
Pronto! Você não precisa mais delegar à sua IDE a tarefa de compilação dos seus arquivos C++! YaY! 

P.S: Segue abaixo, o link do meu projeto de exercícios em C++ com um exemplo estrutural do Make:
https://github.com/emevonlou/learningcpp





domingo, 8 de outubro de 2017




Some C++ Libraries (Algumas Bibliotecas de C++):

#include <iostream>     Input and output functions(Entrada e saída de funções)
#include <cstring>         Functions manipulate some strings(Funções que manipulam                                                   algumas strings.)
#include<cctype>          Functions that manipulate character(Funções que manipulam                                                  caracteres)
#include<cstdlib>          Functions that manipulate character(Funções que manipulam                                                  caracteres)
#include<iomanip>        Functions that manipulate character(Funções que manipulam                                                  caracteres)
#include <studio.h>      Input and output functions(entrada e saída de funções)
#include <string.h>       String related functions( Funções relacionadas a String)
#include <stdlib.h>        Memory allocation, rand and other functions(Alocação de memória,                                        rand e outras funções.)
#include<math.h>         Math functions(Funções de matemática)
#include<time.h>          Time related Functions(Funções relacionadas ao tempo)


Functions(Funções)

returnType functionName (input1Type  inputName, input2Type input2Name,...)
{
 // do something(Faça alguma coisa) 
return value; (valor de retorno)    // value must be of type returnType(o valor deve ser do                                                              tipo returnType
}


Comments(Comentários)

//  This is a C++ style one line  comment.(Este é um estilo C++ de comentário de uma linha)
/* multiple line is a traditional C++ style block comment.( Multiplas linhas é um estilo                                                                                                        tradicional de blocos de                                                                                                              comentários em C++.)

Variable types
---variáveis-------------------------------Bits--------------------------------Range----------------------
int                                                    16                               -32768 to -32767
unsigned int                                    16                                    0 to 65535
signed int                                        16                                -31768 to 32767
short int                                           16                                -31768 to 32767
unsigned short int                           16                                     0 to 65535
signed short int                               16                                -32768 to -32767
long int                                            32                        -2147483648 to 2147483647
unsigned long int                            32                        -2147483648 to 2147483647
signed long int                                32                                 0 to 4294967295 
float                                                32                               3.4E-3O8 to 3.4E- 8
double                                            64                             1.7E-3O8 to 1.7E-3O8
long double                                    80                           3.4E-4932 to 3.4E-4932
char                                                 8                                      -128 to 127
unsigned char                                 8                                        0 to 255
signed char                                     8                                     -128 to 127



P.S: In this post, the information revealed severely accompanies my study frequency. Libraries and other information are based on data I have been given so far. I'm doing baby steps, but always ahead. Forward buddies!



sexta-feira, 6 de outubro de 2017

When I started my studies in programming languages, I came across a series of terms that are foreign to my everyday philosophy, so that the acronym "WTF" does not leave my head. It was a new cycle of experiences that had begun, bordering on other dreams, realizing in me the need to live it with the same intensity that I felt all at first sight. I realized with this, an absolute desire to familiarize myself with the "keywords" referring to the C ++ language, and decided today, to share this first experience with you.

C++ language keywords:

keyword(palavra-chave) Description(Descrição)
and ------------------------------------- alternative to && operator 
and_eq ----------------------------------- alternative to &= operator
asm ---------------------------------------- insert an assembly instruction
auto --------------------------------------- Declare a local variable, or we can let the compiler to deduce the type of the variable from the inicialization)
bitand -------------------------------------- alternative to bitwise & operator
bitor ----------------------------------------- alternative to | operator
bool ------------------------------------------ declare a boolean variable
break ----------------------------------------- break out of a loop
case ------------------------------------------- a block of code in a switch statement
catch ------------------------------------------ handles exeptions from trow
char ------------------------------------------- declare a character variable
class ------------------------------------------- declare a class
compl ----------------------------------------- alternative to ~ operator
const ------------------------------------------ declare immutable data or functions that do not change data
const_cast ----------------------------------- cast from const variables
continue -------------------------------------- bypass iterations of a loop
default ---------------------------------------- default handler in a case statement
#define ---------------------------------------- all header files should have #define guards to prevent multiple inclusion
delete ------------------------------------------ make dinamic memory available
do ----------------------------------------------- looping construct
double ------------------------------------------ declare a double precision floating-point variable
dynamic_cast ---------------------------------- perform runtime casts
else ----------------------------------------------- alternate case for an if statement
enum --------------------------------------------- create enumeration types
exit()----------------------------------------------- ending a process
explicit ------------------------------------------- only use constructors when they exactly match
export--------------------------------------------- Allows template definitions to be separated from theis declarations
extern---------------------------------------------declares a variable or function and specifies that it has external linkage
Extern “C”---------------------------------------- enables C function call from C++ by forcing C-linkage
false----------------------------------------------- a constant representing the boolean value
float------------------------------------------------declare a float-point variable
friend----------------------------------------------- grant non-member function access to private data
goto------------------------------------------------jump to a diferent part of the program
if----------------------------------------------------execute code based on the result of a test
inline----------------------------------------------optimize calls to short functions
int--------------------------------------------------declare a integer variable
long------------------------------------------------declare a long integer variable
mutable-------------------------------------------override a const variable
namespace---------------------------------------partition the global namespace by defining a scope
new------------------------------------------------Allocate dynamic memory of a new variable
not------------------------------------------------- alternative to ! Operator
not_eq --------------------------------------------alternative to != operator
operator-------------------------------------------creat overloaded operator functions
or--------------------------------------------------- alternative to || operator
or_eq----------------------------------------------- alternative to |= operator
private----------------------------------------------declare private members of a class
protected-------------------------------------------declare protected members of a class
public-----------------------------------------------declare public members of a class
register---------------------------------------------request that a variable be optimized for speed
reinterpret_cast----------------------------------- change the type of a variable
short------------------------------------------------- declare a short integer variable
signed-----------------------------------------------modify a variable type declarations
sizeof------------------------------------------------return the size of a variable or type
static------------------------------------------------create a permanent storage for a variable
static_cast-----------------------------------------perform a nonpolymorphic cast
stuct-------------------------------------------------define a new structure
switch----------------------------------------------- execute code based on diferent possible values for a variable
template-------------------------------------------- create generic functions
this-------------------------------------------------- a pointer to the current object
throw------------------------------------------------throws an exeption
true--------------------------------------------------A constant representing the boolean true value
try----------------------------------------------------execute code that can throw an exception
typedef----------------------------------------------create a new type name from a existing type
typeid-----------------------------------------------describes an object
typename-------------------------------------------declare a class or undefined type
union------------------------------------------------a structure that assigns multiple variables to the same memory location
unsigned-------------------------------------------declare an unsigned integer variable
using------------------------------------------------import complete or partial namespaces into the current scope
virtual-----------------------------------------------create an function that can be overriden by a derived class
void-------------------------------------------------declare functions or data with no associaded data type
volatile---------------------------------------------warn the compiler about variables that can be modified unexpectedly
wchar_t--------------------------------------------declare a wide-character variable
while-----------------------------------------------looping construct
xor-------------------------------------------------alternative to ^ operator
xor_eq--------------------------------------------alternative to ^= operator