What exactly are C++ definitions, declarations and

2019-01-09 07:08发布

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 the first time I assign to a variable? Or is there more to it than that?

8条回答
再贱就再见
2楼-- · 2019-01-09 07:34

A definition is where a value or function is described, i.e. the compiler or programmer is told precisely what it is, e.g.

int foo()
{
  return 1;
}

int var; // or, e.g. int var = 5; but this is clearer.

A declaration tells the compiler, or programmer that the function or variable exists. e.g.

int foo();
extern int var;

An assignment is when a variable has its value set, usually with the = operator. e.g.

a = b;
a = foo();
查看更多
走好不送
3楼-- · 2019-01-09 07:36

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
查看更多
登录 后发表回答