Variables in C++

In C++, variables are explicitly declared and used by the compiler to check type-correctness of function calls, among other things.

#include <iostream>
#include <string>

int main() {
    // Declares and initializes a variable
    std::string a = "initial";
    std::cout << a << std::endl;

    // You can declare multiple variables at once
    int b = 1, c = 2;
    std::cout << b << " " << c << std::endl;

    // C++ will infer the type of initialized variables using auto
    auto d = true;
    std::cout << std::boolalpha << d << std::endl;

    // Variables declared without initialization are not guaranteed to be zero-valued
    // It's a good practice to initialize them explicitly
    int e = 0;
    std::cout << e << std::endl;

    // C++ doesn't have a direct equivalent to Go's := syntax
    // But you can use auto for type inference
    auto f = "apple";
    std::cout << f << std::endl;

    return 0;
}

To compile and run the program:

$ g++ -std=c++11 variables.cpp -o variables
$ ./variables
initial
1 2
true
0
apple

In C++, variables are typically declared with their type explicitly stated. However, C++11 introduced the auto keyword, which allows the compiler to deduce the type of a variable from its initializer.

Unlike Go, C++ doesn’t guarantee that uninitialized variables will be zero-valued. It’s a good practice to always initialize variables in C++.

C++ doesn’t have a direct equivalent to Go’s := syntax for short variable declaration. However, the auto keyword can be used for type inference when initializing variables.

Remember that in C++, you need to include the necessary headers (like <iostream> for input/output operations and <string> for string handling) and use the std:: namespace prefix (or a using namespace std; directive) to access standard library features.

C++ also requires a return statement at the end of the main function, typically returning 0 to indicate successful execution.