Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the result of an initialization in C++?

What is the return value of an initialization? For example: In the following code;

#include<iostream>

int main()
{
    int age = 30;          //does this statement return (thus; yield) anything?

    while(int i = 0){      //a similar statement (expression) used here in this condition
        std::cout<<"OK";   
    }

    return 0;
}
  • What does the statement int age = 27; return?
  • Does the usual assignment operator meaning apply when there is an initialization, where the left operand of the assignment operator is returned?

The reason why I want to know this is that, when we take a look at the conditional statement above we see a similar initialization of a variable that is used as the condition. I know that whatever value that is returned is converted to the bool type though.

Note: I am not trying to compare i to 0 in the condition of the while statement.

like image 896
octopus Avatar asked Dec 11 '19 21:12

octopus


People also ask

What happens when you initialize a variable in C?

Static Initialization: Here, the variable is assigned a value in advance. This variable then acts as a constant. Dynamic Initialization: Here, the variable is assigned a value at the run time. The value of this variable can be altered every time the program is being run.

What is initialization in C?

Initialization is the process of locating and using the defined values for variable data that is used by a computer program. For example, an operating system or application program is installed with default or user-specified values that determine certain aspects of how the system or program is to function.

What happens when you initialize a variable?

Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.

Why is initialization important in C?

This refers to the process wherein a variable is assigned an initial value before it is used in the program. Without initialization, a variable would have an unknown value, which can lead to unpredictable outputs when used in computations or other operations.


1 Answers

A declaration statement with an initializer is a just a declaration statement, not an expression. It does not yield a value. You can't do something like int x = (int n = 42);.

The while loop is something of a special case. You can use a declaration as the condition of a while loop. According to cppreference.com,

If this is a declaration, the initializer is evaluated before each iteration, and if the value of the declared variable converts to false, the loop is exited.

like image 186
Fred Larson Avatar answered Oct 22 '22 10:10

Fred Larson