What exactly are C++ definitions, declarations and assignments?

前端 未结 8 1249
长情又很酷
长情又很酷 2020-11-30 08:52

I tend to use the words define, declare and assign interchangeably but this seems to cause offense to some people. Is this justified? Should I only use the word declare for

相关标签:
8条回答
  • 2020-11-30 09:46

    The differences can seem subtle, but they are important. Not every language makes the same distinctions, but in C++ a variable declaration makes the type and name of the variable known to the compiler

    int i;
    

    A variable definition allocates storage and specifies an initial value for the variable.

    i = 1;
    

    You can combine a variable declaration and definition into one statement, as is commonly done.

    int x = 1;
    

    Declaring a variable inside a function will also set aside memory for the variable, so the following code implicitly defines variable a as a part of its declaration.

    int main()
    {
        int a;
        return 0;
    }
    

    Since variable a is automatically defined by the compiler, it will contain whatever value was in the memory location that was allocated for it. This is why it is not safe to use automatic variables until you've explicitly assigned a known value to them.

    An assignment takes place any time you change the value of a variable in your program.

    x = 2;
    x++;
    x += 4;
    

    A function declaration, similar to the variable declaration, makes the function signature known to the compiler. This allows you to call a function in your source code before it is defined without causing a compiler error.

    int doSomething(float x);
    

    A function definition specifies the return type, name, parameter list, and instructions for a function. The first three of these elements must match the function declaration. A function must only be defined once in a given program.

    int doSomething(float x)
    {
        if( x < 0 )
        {
            x = -x;
        }
        return static_cast<int>(x);
    }
    

    You can combine the function decalartion and definition into one, but you must do so before the function is called anywhere in your program.

    0 讨论(0)
  • 2020-11-30 09:54

    Define and declare are similar but assign is very different.

    Here I am declaring (or defining) a variable:

    int x;
    

    Here I am assigning a value to that variable:

    x = 0;
    

    Here I am doing both in one statement:

    int x = 0;
    

    Note

    Not all languages support declaration and assignment in one statement:

    T-SQL

    declare x int;
    set x = 0;
    

    Some languages require that you assign a value to a variable upon declaration. This requirement allows the compiler or interpreter of the language to infer a type for the variable:

    Python

    x = 0
    
    0 讨论(0)
提交回复
热议问题