The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science

Programming Languages and Tools:

CS:3210:0001

Lecture/Lab #3

Programming with C++

Declaration vs definition, function declaration, variables and types

Warm-up

import os

print( "Current directory:",
      os.getcwd() )
#include <iostream>
#include <filesystem>

int main() {
    std::cout 
       << "Current directory: " 
       << std::filesystem::current_path() 
       << "\n";
}

Python

C++

Can we do this in C++?

int main() {
    print( "Current directory:", getcwd() );
}

Exercise 1

Provide definitions of functions `print` and `getcwd` to make the program compile and produce the expected output

  • Open the exercise template

  • Write your code, press Run to test

  • When you're done, grab your Repl's link and send it as a direct message to me (agurtovoy)

  • Click on the corresponding option in the "Lab3 exercises" poll in #general

Instructions

Declaration vs definition

void hello( std::string name );

int main() {
    hello( "Bob" );
}
  • A declaration makes a name known to the compiler and associates it with a type.

  • A definition creates/provides an implementation of the associated entity.

  • C++ allows multiple declarations of the same entity as long as declarations are identical.

  • Only one entity definition is allowed.

  • A declaration allows us to use the entity, but we need to provide the definition eventually to be able to compile the program into an executable.

Function declaration

void hello( std::string );
void hello( std::string name );
void hello( std::string fist_name );
void hello( std::string ignored ) {}

int main() {
    hello( "Bob" );
}
  • Function parameter names are optional

  • Function parameter names can vary between declarations

  • Function parameter names can vary between a declaration and the definition

Exercise 2

Fix the program's compilation errors without changing the order of function definitions

  • Open the exercise template

  • Write your code, press Run to test

  • When you're done, grab your Repl's link and send it as a direct message to me (agurtovoy)

  • Click on the corresponding option in the "Lab3 exercises" poll in #general

Instructions

Variables and types

#include <iostream>

int main()
{
    int n = 42;
    float pi = 3.14;
    bool b = pi < 5;
    char c = 'A';

    std::cout 
        << "n: " << n << "\n"
        << "pi: " << pi << "\n"
        << "b: " << b << "\n"
        << "c: " << c << "\n"
        ;
}
  • Every program entity has a type that determines the operations that may be performed on it
  • For variables, type also determines their size, memory layout, and the range of supported values

Programming with C++, Spring 2020, Lecture #3

By Aleksey Gurtovoy

Programming with C++, Spring 2020, Lecture #3

Declaration vs definition, function declaration, variables and types

  • 638