Skip to content

Sintaxis basica

In C++ you usually work with files and a project folder structure. To start (and to grow without chaos), use one of these two setups:

  • Create a folder, e.g. my-project/
  • Inside it, create main.cpp

Structure:

my-project/
main.cpp

Structure:

my-project/
CMakeLists.txt
src/
main.cpp
greeting.cpp
include/
greeting.h
  • src/: source code (.cpp)
  • include/: headers (.h) with declarations (what a function/class “promises”)
  • CMakeLists.txt: build configuration file for CMake

Minimal program (and what each part means)

Section titled “Minimal program (and what each part means)”
#include <iostream>
int main() {
std::cout << "Hola C++" << std::endl;
return 0;
}
  • #include <iostream>: imports the standard input/output library so you can use std::cout.
    • <> means it’s a standard library header.
  • int main(): program entry point. Most console programs start here.
    • int means the function returns an integer to the operating system.
  • { ... }: braces define the block of code that belongs to main.
  • std::cout: output to the console (terminal).
  • <<: “insertion” operator used to send data into cout.
  • std::endl: newline + flush. You can also use "\n" in many cases.
  • ; (semicolon): ends a statement.
  • return 0;: means “finished successfully”. (Modern C++ compilers often assume 0 if omitted in main, but we keep it explicit here.)

Basic syntax rules (common beginner pitfalls)

Section titled “Basic syntax rules (common beginner pitfalls)”
  • Case matters: Main is not the same as main.
  • Most statements end with ; (except constructs like if (...) {}).
  • Braces control structure: they define what belongs to an if, for, while, functions, classes, etc.
  • Indentation: doesn’t change meaning, but it makes code readable. Use 2 or 4 spaces consistently.
// Single-line comment
/*
Multi-line
comment
*/
int age = 20; // integer
double pi = 3.14159; // floating point
char letter = 'A'; // one character
bool active = true; // true/false
int grade = 15;
if (grade >= 10) {
std::cout << "Passed\n";
} else {
std::cout << "Failed\n";
}
for (int i = 0; i < 5; i++) {
std::cout << i << "\n";
}
int j = 0;
while (j < 5) {
std::cout << j << "\n";
j++;
}

If you’re using the recommended structure, create a minimal CMakeLists.txt like this:

cmake_minimum_required(VERSION 3.16)
project(my_project LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_executable(my_project
src/main.cpp
)

Then, in a terminal inside your project folder:

Ventana de terminal
cmake -S . -B build
cmake --build build

This will generate the executable inside build/ (exact name/location depends on your OS).

Agrega aqui operadores, condicionales, ciclos y ejemplos de clase.