Rajat Sharma
Rajat Sharma

Reputation: 11

How c++ is compiled? (Regarding variable declaration)

So I went through this video - https://youtu.be/e4ax90XmUBc

Now, my doubt is that if C++ is compiled language, that is, it goes through the entire code and translates it, then if I do something like

void main() {
   int a;
   cout<<"This is a number = "<<a;   //This will give an error (Why?)
   a = 10;
}

Now, answer for this would be that I have not defined the value for a, which I learned in school. But if a compiler goes through the entire code and then translates it then I think it shouldn't give any error. But by giving an error like this, it looks to me as if C++ is a interpreted language. Can anyone put some light on this and help me solve my dilemma here?

Upvotes: 1

Views: 138

Answers (1)

janekb04
janekb04

Reputation: 4915

Technically, the C++ standard doesn't mandate that the compiler has to compile C++ into machine code. As an example LLVM Clang first compiles it to IR (Intermediate Representation) and only then to machine code.

Similarly, a compiler could embed a copy of itself in a program that it compiles and then, when the program is executed compile the program, immediately invoke it and delete the executable afterwards which in practice would be very similar to the program being interpreted. In practice, all widely used C++ compilers parse and assemble programs beforehand.

Regarding your example, the statement "This will give an error" is a bit ambiguous. I'm not sure if you're saying that you're getting a compile-time error or a runtime error. As such, I will discuss both possibilities.

If you're getting a compile time error, then your compiler has noticed that your program has undefined behaviour. This is something that you always want to avoid (in some cases, such as when your application operates outside the scope of the C++ Standard, such as when interfacing with certain hardware, UB occurs by definition, as certain behaviour is not defined by the Standard). This is a simple form of static analysis. The Standard doesn't mandate the your compiler informs you of this error and it would usually be a runtime error, but your compiler informed you anyway because it noticed that you probably made a mistake. For example on g++ such behaviour could be achieved by using the -Wall -Werror flags.

In the case of the error being a runtime error then you're most likely seeing a message like "Memory Access Violation" (on Windows) or "Signal 11" (on Linux). This is due to the fact that your program accessed uninitialized memory which is Undefined Behaviour.

In practice, you wouldn't most likely get any error at all at runtime. Unless the compiler has embedded dynamic checks in your program, it would just silently print a (seemingly) random value and continue. The value comes from uninitialized memory.

Side note: main returns int rather than void. Also using namespace std; considered harmful.

Upvotes: 1

Related Questions